ways dp table · the code only keeps the cells under one and two
public int climbStairs(int n) { int one = 1; // ways[1] int two = 1; // ways[0] for (int i = 2; i <= n; i++) { int temp = one; one = one + two; // ways[i] two = temp; } return one;}
- n
- —
- i
- —
- one
- —
- two
- —
- temp
- —
Why it works
- Brute force recurses:
climb(n) = climb(n−1) + climb(n−2). Each call spawns two more, so the call tree has about 1.6ⁿ leaves, O(2ⁿ).climb(n−2)is solved again insideclimb(n−1), and so on down. - The last move decides: you reach step
iby a +1 fromi−1or a +2 fromi−2. Those two groups never overlap, soways[i] = ways[i−1] + ways[i−2], withways[0] = ways[1] = 1. That is Fibonacci, shifted by one. - Memoise, then go bottom-up. Caching each
climb(i)makes it O(n) time and O(n) space. Filling the table from 0 upward does the same without recursion. - Only two cells are ever read, so two variables replace the table: O(1) space. Watch the order:
one = one + two; two = onewould copy the new value. Save the old one intemp, or computeint next = one + two;first, thentwo = one; one = next;. - It grows fast: about ×1.6 per step. LeetCode stops at n = 45 (1,836,311,903 ways) so the answer fits an
int. - Follow-ups: Min Cost Climbing Stairs uses the same two-cell window with
min. Moves of {1, 2, 3} add a third term. For huge n, matrix power gives O(log n). House Robber, next, adds a choice at each step.