A staircase has n steps. Each move climbs either a single step or two steps at once. Return how many different sequences of moves take you from the bottom to the top.
Examples
Example 1:
Input: n = 2
Output: 2
Example 2:
Input: n = 3
Output: 3
Example 3:
Input: n = 5
Output: 8
Constraints
1 <= n <= 45
Prerequisites
Dynamic programming — being able to say, in one sentence, what a single cell of your table MEANS. Everything else follows from that sentence. Rolling variables: when a state only looks back one or two steps, the table collapses to a couple of numbers.
How to think about it
1. Count Each Step From the Two Below Optimal
Intuition
The last move onto a step is either a single step from the step below it or a double from two below, and no way to the top makes both. So the ways to reach a step are the ways to reach the step below plus the ways to reach the step two below: each step's count is the sum of the counts of the two steps below it. Write the counts in a table from the ground up, and each one is ready when the next needs it.
Algorithm
1. Make a table, ways, of n + 1 counts: one for the ground, step 0, and one for each step. 2. The ground has one way, which is not to move: ways[0] = 1. The first step has one, a single step: ways[1] = 1. 3. For each step from 2 to n, ways[step] = ways[step - 1] + ways[step - 2]. 4. Return ways[n].
Time & Space
Time O(n): each step is filled once. Space O(n) for the table; two counts in its place make it O(1).
2. Fibonacci in Disguise Optimal
Intuition
The last move onto step n was either a single step from n-1 or a double from n-2, and those two sets of routes share nothing — so the count is their sum. That is the Fibonacci recurrence, and recognising it is the whole problem. Two rolling variables replace the table, because a step never looks further back than two.
Algorithm
1. One step: one way. Two steps: two ways. 2. Walk upward keeping the counts for the previous two steps. 3. Each step's count is their sum.
Time & Space
Time O(n). Space O(1) with rolling variables; the naive recursion is exponential without memoisation, which is worth saying.