What is Climbing Stairs
To reach stair n you last stepped from n−1 or n−2. So the number of ways is Fibonacci: dp[n] = dp[n-1] + dp[n-2]. Memoizing (or filling bottom-up) turns an exponential tree into a linear scan.
Brute force approach
f(n) = f(n-1) + f(n-2). The same f(k) is recomputed from many parents. Time O(2^n).ways(n) asks for ways(n-1) and ways(n-2). The brute-force tree repeats those calls. Memoization stores each n the first time it is solved.
Keep n at 4 or below so the whole recursion tree fits in the canvas. ways(1) = 1 and ways(0) = 1, so ways(2) = 2.
Memoized approach
dp[1..n] or keep two rolling numbers. Time O(n), space O(1).Each state is solved once. A dashed node is a cache hit: the call returns immediately and that branch stops.
Interactive DP trace
Pseudocode & Complexity
| Operation | Time |
|---|---|
| Each stair | O(1) |
| All stairs | O(n) |
| Space | O(1) |
Brute force explores the same subproblems many times and will TLE on the hidden tests. The DP codes below reuse each answer once.
Implementations