Climbing Stairs Problem
Description
LeetCode Problem 70.
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 1:
Input: n = 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
- 1 <= n <= 45
Solution
Approach: Dynamic Programming (Fibonacci)
Look at the last move. To stand on step i, you either came from step i - 1 with a 1-step, or from step i - 2 with a 2-step. These two groups do not overlap and together cover every way to reach step i, so
ways(i) = ways(i - 1) + ways(i - 2),
with ways(0) = 1 (standing at the bottom, doing nothing) and ways(1) = 1. These are the Fibonacci numbers.
Writing this as plain recursion recomputes the same steps again and again and takes exponential time. Computing it from the bottom up avoids that, and since each value only needs the two before it, two variables are enough:
twoBelow = 1,oneBelow = 1(for steps 0 and 1).- For
ifrom 2 ton:current = oneBelow + twoBelow, then shift:twoBelow = oneBelow,oneBelow = current. - Return
oneBelow.
For n = 3: ways(2) = 2, ways(3) = 3. The largest answer, for n = 45, is 1,836,311,903, which still fits in a 32-bit integer.
Complexity: O(n) time and O(1) space.
class Solution:
def climbStairs(self, n: int) -> int:
# ways(i) = ways(i - 1) + ways(i - 2): the last move is a 1-step or a 2-step.
two_below, one_below = 1, 1 # ways(0) and ways(1)
for _ in range(2, n + 1):
current = one_below + two_below
two_below = one_below
one_below = current
return one_below
Now write it from memory
Close the write-up and solve it yourself against the tests.