Intuition
The first move from step 0 is either +1 (then we still need f(n-1) ways to finish from step 1) or +2 (then we need f(n-2) ways from step 2). So f(n) = f(n-1) + f(n-2) — Fibonacci. Direct recursion captures the recurrence but pays for it: it re-solves the same subproblems exponentially many times.
Explanation
The recurrence
f(n) = f(n-1) + f(n-2) with base cases f(1) = 1, f(2) = 2.
Why f(2) = 2? You can climb (1, 1) or (2). Two ways.
Steps
- Base case: if
n <= 2, returnn. - Else return
climbStairs(n - 1) + climbStairs(n - 2).
Walk-through
climbStairs(5) expands as:
f(5) = f(4) + f(3)
= (f(3) + f(2)) + (f(2) + f(1))
= ((f(2) + f(1)) + 2) + (2 + 1)
= ((2 + 1) + 2) + 3
= 5 + 3
= 8
Why exponential
Each call branches into two more calls of nearly the same size, so the call-tree size grows like 2ⁿ. Concretely, climbStairs(30) makes over a million calls — already slow.
Complexity
- Time:
O(2ⁿ). - Space:
O(n)recursion depth.
Implementation
class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
}
}