
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
climb_ways(n): the number of ways to climbnstairs, taking 1 or 2 at a time. Build the table bottom-up and returnways[n].climb_ways(0)is1andclimb_ways(3)is3.climb_ways_3(n): the same, but Pip can also take 3 stairs at once. Nowways[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)is7.- Both must be fast for
n = 80, so don't use plain recursion.
climb_ways(n): the number of ways to climbnstairs, taking 1 or 2 at a time. Build the table bottom-up and returnways[n].climb_ways(0)is1andclimb_ways(3)is3.climb_ways_3(n): the same, but Pip can also take 3 stairs at once. Nowways[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)is7.- Both must be fast for
n = 80, so don't use plain recursion.
Press Run to try your code, then Check to test it.