Dynamic programmingAnimated
Climbing Stairs
Ways to reach step n = ways(n−1) + ways(n−2).
Time
O(n)
Extra space
O(1)
Use it for
Counting paths with fixed moves.
How it works
- You can climb 1 or 2 steps at a time. How many different ways reach step n?
- The last move was either from step n−1 (a 1-step) or step n−2 (a 2-step).
- So ways(n) = ways(n−1) + ways(n−2). Base: ways(0) = 1, ways(1) = 1.
- Fill the table upwards: O(n).
Watch it run
Loading animation…