Dynamic programming
Build a table of useful subproblem answers, then use it to count staircase paths.
ways = [0] * (stairs + 1)ways[0] = 1for index in range(1, stairs + 1): ways[index] = ways[index - 1] if index >= 2: ways[index] += ways[index - 2]return ways[stairs]Each position will hold the number of ways to reach that stair.
Define exactly what the state means
ways[i] is the number of ordered hop sequences that climb exactly i stairs using hops of one or two stairs. There is one way to climb zero stairs: take no hops. There is one way to climb one stair.
How it works
Say what the stored answer means in one sentence before writing a formula. For a staircase, ways[i] is the number of ways to reach step i. A last move of length 1 comes from step i−1, and a last move of length 2 comes from step i−2. These choices are separate, so add their counts.
Use the last move
Every sequence ends with a one-stair or a two-stair hop. The prefix of the first kind climbs i - 1 stairs. The second climbs i - 2. The two kinds do not overlap, so their counts add: ways[i] = ways[i - 1] + ways[i - 2].
Choose the table order
Fill the answers from zero upward so both dependencies are known when needed. Filling a table through n uses O(n) time and O(n) additional space. If you only need the final count, keep the two latest counts and use O(1) additional space. The samples use small inputs to avoid fixed-width overflow or lost integer precision.
Code example
def ways_to_climb(stairs):
ways = [0] * (stairs + 1)
ways[0] = 1
for i in range(1, stairs + 1):
ways[i] = ways[i - 1]
if i >= 2:
ways[i] += ways[i - 2]
return ways[stairs]
print(ways_to_climb(4))Check your understanding
Count ordered ways to climb exactly n stairs, using one- or two-stair moves.
See the example and explanation
- Example 1
- Given
n = 0 - Answer
1 - Example 2
- Given
n = 3 - Answer
3 - Example 3
- Given
n = 4 - Answer
5
The table begins 1, 1, 2, 3, 5. A hop sequence finishing at stair 4 either comes from stair 3 or stair 2, giving 3 + 2 = 5 arrangements.