Problem Description
You are given a staircase with n steps. At each move, you can take either 1 step or 2 steps. The goal is to determine the number of distinct ways to reach the top.
Key Insights
- The problem can be solved using dynamic programming because the solution for a given step depends on the solutions of the previous two steps.
- The recurrence relation is: ways[i] = ways[i-1] + ways[i-2].
- Base cases: when there is 1 step, there is 1 way; when there are 2 steps, there are 2 ways.
- This is analogous to the Fibonacci sequence, shifting indices accordingly.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (can be optimized to O(1) using constant space)
Solution
We use a dynamic programming approach to build a solution gradually. The idea is that to reach step i, you could have come from step i-1 (taking one step) or from step i-2 (taking two steps). Therefore, the total number of ways to reach step i is the sum of ways to reach step i-1 and i-2. We initialize dp[1] = 1 and dp[2] = 2, and iterate from 3 to n to fill dp[]. Each code solution below uses this approach with comments to explain the logic.