Skip to content
BytePatterns

Climbing Stairs

Dynamic Programming: lesson 3 of 20

Ways to reach step n = ways to n-1 plus ways to n-2.

Lesson 3 of 20 · 4 min

Climbing Stairs

Step 1 of 7

One cell per step of the staircase. ways(0) = ways(1) = 1 — the two base cases you can write down without thinking.

The Idea

You may step up one stair or two. To be standing on step n you must have arrived from step n-1 or from step n-2, so the ways to reach n are those two counts added together. That is Fibonacci wearing a different hat, and because nothing older is ever read, two rolling variables replace the entire table.

Real-World Example

Planking a one-metre-wide hallway with boards one and two metres long. The number of layouts for a ten-metre hall is the layouts for nine metres plus the layouts for eight, because the last board laid is either a short one or a long one.

The Code

def climb(n):
    a, b = 1, 1                  # ways to reach step 0 and step 1
    for _ in range(2, n + 1):
        a, b = b, a + b          # slide the window forward one step
    return b

print(climb(5))    # 8
print(climb(10))   # 89

Python

Your turn

Fill in the blank.

def climb(n):
  a, b = 1, 1
  for _ in range(2, n + 1):
      a, b = b, ___
  return b

print(climb(6))   # should print 13

Mini quiz

1 / 3

With 1- and 2-step moves, ways(n) equals:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.