Recursion (Brute Force)
Intuition
At each step we have two choices: take 1 step or take 2 steps. This naturally forms a recursive tree where climbStairs(n) = climbStairs(n-1) + climbStairs(n-2). The base cases are climbStairs(1) = 1 and climbStairs(2) = 2. While simple, this recurrence recomputes the same subproblems exponentially many times.
Algorithm
- If `n <= 2`, return `n` directly.
- Recursively compute the number of ways to reach step `n-1` and step `n-2`.
- Return the sum of those two values.
O(2^n)SpaceO(n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int climbStairs(int n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
}
};class Solution {
public int climbStairs(int n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
}
}class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
return self.climbStairs(n - 1) + self.climbStairs(n - 2)func climbStairs(n int) int {
if n <= 2 {
return n
}
return climbStairs(n-1) + climbStairs(n-2)
}