Climbing Stairs – Solution & Complexity
1. Understand the Choices
- At each move, you can climb either 1 step or 2 steps.
- To reach step
n, the last move must come from stepn - 1or stepn - 2. - Therefore, ways to reach
nequals ways to reachn - 1plus ways to reachn - 2.
2. Recognize the Fibonacci Pattern
- For
n = 1, there is 1 way:1. - For
n = 2, there are 2 ways:1+1and2. - Every later answer is the sum of the previous two answers.
3. Avoid Recomputing Subproblems
- A naive recursive solution branches into
n - 1andn - 2repeatedly. - That repeats the same calculations many times.
- Dynamic programming stores or carries forward the previous answers instead.
4. Keep Only the Last Two Values
- You do not need a full array because each state depends only on the previous two states.
- Let
one_backrepresent ways to reach the previous step. - Let
two_backrepresent ways to reach the step before that.
5. Final Solution and Complexity
- Iterate from step 3 through step
n, adding the last two counts each time. - Time complexity is O(n).
- Space complexity is O(1) because only two counts are stored.