Climbing stairs
Easy TimeO(2ⁿ) naive, O(n) memoised SpaceO(n)
A staircase has n steps, and each move takes either 1 or 2 of them, nothing else. Return how many distinct ways there are to reach the top — 5 steps give 8. Two climbs are different when the order of their moves differs, so 1 + 2 and 2 + 1 both count. n is at least 1.
Examples
Example 1
- Input
- n = 5
- Output
- Five 1s; three 1s and a 2 in 4 orders; one 1 and two 2s in 3 orders —
81 + 4 + 3= 8.
Example 2
- Input
- n = 1
- Output
- One step, and a single move is the only thing that reaches it.
1
The Code
function climbStairs(n) {
if (n <= 2) return n;
return climbStairs(n - 1) + climbStairs(n - 2);
}
climbStairs(5);Done
More like this
All dynamic programming examples (20) →- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.
- House robber Rob a house and skip its neighbour, or skip to the next.