Algorithms · Dynamic programming

Climbing Stairs

1 or 2 steps at a time: how many ways up?

The problem

You can climb 1 or 2 steps at a time. How many different ways are there to climb n steps?

ways(2)2
ways(3)3
Dynamic programming. Write the answer down. A sticky note for every sum you’ve worked out, so you never work it out twice.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def ways(n):take the number of steps
if n <= 1:zero or one step left…
return 1…only one way to do it
return ways(n - 1) + ways(n - 2)the last move was 1 step, or 2 steps

Now ask: what if there were a billion?

Writing answers down to reuse them is how GitHub can show you a diff between two huge files: a table of small answers (“how similar are these two beginnings?”) built up one cell at a time.

Aim for O(n)🌱 warm-up

Think it through

To reach step n, your last move was 1 step or 2 steps. So the ways to reach n are…

  • ways(n − 1) + ways(n − 2)
  • ways(n − 1) × 2
Show the answer

ways(n − 1) + ways(n − 2). Every way to reach n ends with a 1-step from n − 1 or a 2-step from n − 2. Add them. (It’s Fibonacci!)

The obvious recursion works out ways(2) how many times for n = 30?

  • Once
  • Hundreds of thousands of times
Show the answer

Hundreds of thousands of times. The same small answers are worked out again and again. Write each down once, or just count upwards with two variables. That’s dynamic programming.

Stuck? 3 nudges, smallest first
  1. Draw the calls for ways(5). How many times does it work out ways(2) from scratch?
  2. Write each answer down the first time you work it out. Every answer only needs the two below it.
  3. Count upwards with two variables: a, b = 1, 1, then repeat a, b = b, a + b.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def ways(n):take the number of steps
a, b = 1, 1ways to climb 0 steps, and 1 step
for _ in range(n - 1):work upwards one step at a time
a, b = b, a + bthe next answer is the sum of the last two
return bways to climb n steps

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with dynamic programming