Back
Dynamic Programming (Hard) / 302. Climbing Stairs
00:00
1/5
302. Climbing Stairs
EasyYou 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
idepends on stepi-1(1 jump) andi-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…