Back

Dynamic Programming (Hard) / 302. Climbing Stairs

00:00
1/5

302. Climbing Stairs

Easy

You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Example:

Input: n = 3
Output: 3
Explanation: 1+1+1, 1+2, 2+1
  • 1

    Subproblem: Reaching step i depends on step i-1 (1 jump) and i-2 (2 jumps).

  • 2

    Recurrence: dp[i] = dp[i-1] + dp[i-2].

  • 3

    Base Cases: dp[1] = 1, dp[2] = 2.

  • 4

    Optimization: Logic is identical to Fibonacci. Space can be O(1) by storing only last two values.

PYTHON PLAYGROUND
PYTHON PLAYGROUND
⏳ Loading editor…