Climbing Stairs easy
Description
Youβre climbing a staircase. It takes n steps to reach the top. Each time you can climb either 1 or 2 steps. In how many distinct ways can you climb to the top?
Examples
> Case 1:
n = 2
Output: 2
Explanation: 1+1, or 2.
> Case 2:
n = 5
Output: 8
Explanation: 1+1+1+1+1, 1+1+1+2, 1+1+2+1, 1+2+1+1,
2+1+1+1, 1+2+2, 2+1+2, 2+2+1Constraints
1 <= n <= 45
State design
- What am I computing? Number of distinct ways to reach step
i. - Dimensions? One β just
i. - Base cases?
dp[0] = 1(one way to be at the start β donβt move),dp[1] = 1. - Transition?
dp[i] = dp[i - 1] + dp[i - 2]. To reach stepi, the last move was a 1-step (fromi - 1) or a 2-step (fromi - 2). - Order? Increasing
i.
The recurrence is Fibonacci with shifted base cases. Same shape, same O(n) solution.
Code
The βI can climb k steps at a timeβ generalization turns this into dp[i] = sum(dp[i - 1], dp[i - 2], ..., dp[i - k]). Same shape, longer window. Interviewers love asking this follow-up.
Analysis
- Time:
O(n)β one pass. - Space:
O(1)β two rolling variables.