← BACK TO KNOWLEDGE
KNOWLEDGE
Climbing Stairs: Dynamic Programming Tabulation
— views— comments
Transform exponential tree recursion into linear O(n) tabulation by identifying overlapping subproblems and optimal substructure.
INTERACTIVE ALGORITHM WORKBENCH
Climbing Stairs (Dynamic Programming) Visualizer
EasyDynamic ProgrammingTime O(n)Space O(n)
1D Dynamic Programming Table (Tabulation)dp[i] = dp[i-1] + dp[i-2]
| Step (i) | 0 | 1 | 2target | 3 | 4 |
| Ways dp[i] | — | 1 | 2 | — | — |
Target Step (n)4
Current Step (i)2
Recurrence AddendsBase cases initialized
Subproblem StatusBase values (1, 2) set
1def climb_stairs(n: int) -> int:▶2 if n <= 2:3 return n4 dp = [0] * (n + 1)5 dp[1], dp[2] = 1, 26 for i in range(3, n + 1):7 dp[i] = dp[i - 1] + dp[i - 2]8 return dp[n]WHY THIS STEP WORKS
Dynamic programming breaks down a problem into overlapping subproblems with optimal substructure. We initialize known trivial base cases first.
- 1Define dp[i] = number of distinct ways to reach step i
- 2Base case: dp[1] = 1
- 3Base case: dp[2] = 2
Comments