How climbing stairs works
The last move onto step i came either from step i − 1 or from step i − 2, so ways[i] = ways[i − 1] + ways[i − 2]. With ways[0] and ways[1] both 1, a single loop fills the table from the bottom up, and each answer is computed exactly once.
The example has 8 stairs and returns 34.
What to watch for when it runs
- Each new cell is built from the two cells just before it.
- Compare with recursive Fibonacci: the same recurrence, but each value is computed once instead of over and over.
- Only the last two cells are ever read, which is why this can be done with two variables and O(1) space.
Time and space complexity
- Time
- O(n)
- Space
- O(n), or O(1) keeping only two values
One pass, constant work per step — against the exponential number of calls the plain recursive version makes.