Code

Fill the Table

In Remember the Answers you cached a recursive function. That is top-down: start with the big problem and recurse down to small ones.

Dynamic programming (DP) often goes the other way: bottom-up. Solve the smallest cases first and write them in a list, called a table. Then build each bigger answer from answers already in the table. No recursion needed!

Climbing the lighthouse

Pip climbs the lighthouse stairs, 1 or 2 stairs at a time. How many different ways can Pip reach stair n?

Think about the last step. To stand on stair n, Pip came from stair n - 1 (a 1-step) or from stair n - 2 (a 2-step). So:

ways[n] = ways[n - 1] + ways[n - 2]

The smallest cases are easy. There is 1 way to stay on stair 0 (do nothing), and 1 way to reach stair 1.

ways = [1, 1]                  # stair 0, stair 1
for i in range(2, 6):
    ways.append(ways[i - 1] + ways[i - 2])
print(ways)  # [1, 1, 2, 3, 5, 8]

Each new entry only looks back at entries that are already filled in. That is the heart of every DP table.

Assignment

  1. climb_ways(n): the number of ways to climb n stairs, taking 1 or 2 at a time. Build the table bottom-up and return ways[n]. climb_ways(0) is 1 and climb_ways(3) is 3.
  2. climb_ways_3(n): the same, but Pip can also take 3 stairs at once. Now ways[n] = ways[n-1] + ways[n-2] + ways[n-3]. The table starts as [1, 1, 2] (stairs 0, 1 and 2). climb_ways_3(4) is 7.
  3. Both must be fast for n = 80, so don't use plain recursion.