Example 1
- Input
- n = 5
- Output
- 8
The routes are [1, 1, 1, 1, 1], [2, 1, 1, 1], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. Order matters: placing a two-step move at different positions creates different routes.
Count how many distinct ways there are to reach step n when every move climbs either 1 or 2 steps.
You are climbing a staircase with n steps. Each move climbs either 1 step or 2 steps.
Return the number of distinct move sequences that land exactly on step n.
1 <= n <= 45The routes are [1, 1, 1, 1, 1], [2, 1, 1, 1], [1, 2, 1, 1], [1, 1, 2, 1], [1, 1, 1, 2], [2, 2, 1], [2, 1, 2], and [1, 2, 2]. Order matters: placing a two-step move at different positions creates different routes.
The three routes are [1, 1, 1], [1, 2], and [2, 1]. The last two contain the same moves in different orders and must both be counted.
Only [1] reaches the first step. A two-step move overshoots, so the smallest valid input has exactly one route.
The two routes are [1, 1] and [2]. This second seed is needed before the recurrence can combine two smaller positive staircases.
Group routes by their final move. A route to step 5 ends with one step from step 4 or two steps from step 3. There are 5 routes to step 4 and 3 to step 3, so step 5 has 8 routes. These groups cannot overlap because their final moves differ. Repeating this reasoning gives a recurrence; remembering the last two counts avoids counting the same smaller staircase again and again.
Reveal Recursion Without Memo: intuition, complexity, and code
When each state depends only on a fixed window of previous states, a recurrence plus a few rolling variables turns exponential recursion into linear time and constant space.