Climbing Stairs
You're climbing a staircase with n steps, starting at the bottom. Each move climbs either 1 step or 2 steps. Return the number of distinct ways to land exactly on step n, where two ways differ if their sequences of moves differ, so 1+2 and 2+1 count separately.
Examples
n = 2 returns 2
Either two single steps (1+1) or one double step (2).
n = 3 returns 3
The sequences are 1+1+1, 1+2 and 2+1. Order matters, so 1+2 and 2+1 are different ways.
Constraints
- 1 <= n <= 45
Hints
Think about the very last move onto the top step. Where could you have been standing just before it?
Dynamic programming: the count for step n is built from the counts for the two steps below it.
ways(1) = 1 and ways(2) = 2. For each step i from 3 to n, ways(i) = ways(i - 1) + ways(i - 2). Keep only the last two values in variables and return the final one.
Drill This: Your Approach First
Approach
The last move onto step n is either a 1-step from step n - 1 or a 2-step from step n - 2, so ways(n) = ways(n - 1) + ways(n - 2), the Fibonacci recurrence. Starting from ways(1) = 1 and ways(2) = 2, build upward while keeping only the last two values in prev2 and prev1, since nothing older is needed again. The loop runs n - 2 times.
Time
O(n)
Space
O(1)
Pitfall
Solutions
class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
int prev2 = 1, prev1 = 2;
for (int i = 3; i <= n; i++) {
int cur = prev1 + prev2;
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev2, prev1 = 1, 2
for _ in range(3, n + 1):
prev2, prev1 = prev1, prev1 + prev2
return prev1