Dynamic programming · Easy

Climbing stairs

You can take 1 or 2 steps. Return the number of ways to climb step_count steps, with step_count >= 0 and one empty way for step_count = 0. Two routes differ when they use a different sequence of one-step and two-step moves.

Worked example

4 → 5

  1. To reach step 3, there are 3 routes. To reach step 2, there are 2 routes.
  2. A route to step 4 ends with a move from step 3 or step 2. Add 3 + 2 to get 5.

Python solution

def solve(step_count):
    previous, current = 1, 1
    for _ in range(step_count):
        previous, current = current, previous + current
    return previous

Ways to reach a step equal the sum of ways to reach its previous two steps.

Time: O(n) · Space: O(1)

Practise in GymType