Fill dp[1..n] left to right; dp[i] = dp[i−1] + dp[i−2].
Start from the base cases and build upward. By the time we compute dp[i], both of its dependencies are already in the table — no recursion, no cache misses, no stack.
Algorithm
- If
n ≤ 2returnn. dp[1] = 1,dp[2] = 2.- For
iin3..n:dp[i] = dp[i−1] + dp[i−2]. - Return
dp[n].
- Time
- O(n)
- Space
- O(n)
class Solution: def climbStairs(self, n: int) -> int: if n <= 2: return n dp = [0] * (n + 1) # dp[i] = ways to reach step i dp[1], dp[2] = 1, 2 for i in range(3, n + 1): dp[i] = dp[i - 1] + dp[i - 2] return dp[n]