Climbing Stairs
Difficulty: Easy · Pattern: 1-D Dynamic Programming · LeetCode #70
A staircase has n steps. Each move climbs 1 or 2 steps. In how many distinct ways can you reach the top?
Examples
text
n = 2 → 2 (1+1, 2)
n = 3 → 3 (1+1+1, 1+2, 2+1)
n = 5 → 8Hints
- The last move onto step n came from step n−1 or step n−2.
- So ways(n) = ways(n−1) + ways(n−2): the Fibonacci recurrence.
- You only need the previous two values.
Approach
State: dp[i] = number of ways to reach step i. The final move is either a 1-step from i−1 or a 2-step from i−2, so dp[i] = dp[i−1] + dp[i−2], with dp[0] = 1 (one way to stand still) and dp[1] = 1. Keep just two variables for O(1) space.
Complexity
Time: O(n). Space: O(1).
Python solution
def climbStairs(n):
a, b = 1, 1 # dp[0], dp[1]
for _ in range(n - 1):
a, b = b, a + b
return bJavaScript solution
function climbStairs(n) {
let a = 1, b = 1;
for (let i = 1; i < n; i++) [a, b] = [b, a + b];
return b;
}