From memoised recursion to dynamic programming
A four-line recursive function can run for minutes on an input of 50, because it solves the same small problem millions of times. Here you find the repeats, cache them, and then turn the cache into a plain loop that fills a table.
01 The same call, again and again
You can climb a staircase one or two steps at a time. How many ways are there to climb n steps? Your first move is either one step, leaving n − 1, or two steps, leaving n − 2. So the answer is the sum of those two answers.
It is correct, and it is slow. Draw every call it makes for ways(5) and the problem is plain to see: the same calls turn up in several branches.
- first call for this n
- already solved elsewhere
ways(3) is solved twice and ways(2) three times. Each repeat also redoes everything below it.
The tree roughly doubles each time n grows by a step or two. ways(30) makes 2,692,537 calls to answer a question that has only 31 different sub-questions, ways(0) to ways(30).
02 Cache each answer the first time
The answer to ways(3) never changes. So the first time you work it out, write it down, and every later call can read it instead of recursing. That written-down store is a memo, and the technique is memoisation.
def ways(n):if n <= 1:return 1return ways(n - 1) + ways(n - 2)
def ways(n, memo):if n <= 1:return 1if n in memo:return memo[n]memo[n] = ways(n - 1, memo) + ways(n - 2, memo)return memo[n]ways(5, {})
Two lines changed: look in the memo before doing any work, and store the result before returning. The recursion itself is untouched. Watch what that does to the calls.
- not called yet
- running
- waiting on a call
- returned
- answered by the memo
- just stored
Nothing has run yet. The memo is an empty dictionary, and no call has been made.
With the memo, each value of n is computed once and every other request is a dictionary lookup. ways(30) drops from 2,692,537 calls to 59: one for each of 2 to 30 doing its two calls, plus the first call. The time goes from exponential to O(n).
In Python, @functools.cache on the plain function does the same thing for you: it keys the cache on the arguments. Writing the dictionary by hand once shows you what it is doing.
03 Look at the order the memo filled in
In the trace the memo filled as 2, 3, 4, 5: smallest first. That is not luck. ways(n) only ever needs answers for smaller n, so the recursion has to dive to the bottom before anything can be stored, and the answers come back up in increasing order.
Once you know that order, you do not need the recursion to discover it. Start with the base cases and work upwards, and every value you need is already there when you need it.
04 Fill the same table bottom-up
Replace the dictionary with a list indexed by n, and the recursive calls with reads of earlier cells. This is what people usually mean by dynamic programming: the same subproblems as the memo, solved in an order you chose.
- not filled yet
- read for this cell
- just filled
- filled earlier
dp has one cell per subproblem, 0 to 5. Nothing is filled yet.
Each cell is filled once and reads two cells, so the loop is O(n) time, the same as the memo. The difference is in how it runs: no call per subproblem, no dictionary, and no stack that grows with n.
05 Memo or table: what changes
| Question | Memoised recursion | Bottom-up table |
|---|---|---|
| Who picks the order | The recursion, as it needs answers | You, smallest first |
| Subproblems solved | Only the ones the question reaches | Every cell in the table |
| Call stack | Up to n frames deep | None: it is a loop |
| Easiest to write | Straight from the recurrence | Once you know the fill order |
| Saving memory | Hard: the memo keeps everything | Easy: keep only the cells still read |
That last row matters here. dp[i] only reads the two cells just before it, so once i has moved on, older cells are never read again. Two variables are enough.
dp = [0] * (n + 1)dp[0] = dp[1] = 1for i in range(2, n + 1):dp[i] = dp[i - 1] + dp[i - 2]return dp[n]
prev, cur = 1, 1 # ways(0), ways(1)for _ in range(2, n + 1):prev, cur = cur, prev + curreturn cur
06 The recipe, on a harder problem
The steps you just took work for most dynamic programming problems. Write the recursion first, because that is where the thinking is. The rest is mechanical.
- Name the state. What does one subproblem need to know? For the stairs, just
n. - Write the recurrence. Try every first move and combine the answers for what is left.
- Memoise it. Key the cache on the whole state, every argument that changes the answer.
- Find the order. Which states does each one read? Fill those first.
- Turn it into a loop, and then drop the cells you never read again.
| Step | Climbing stairs | Coin change (fewest coins) |
|---|---|---|
| State | n steps left | amount a left to pay |
| First move | climb 1 or 2 | use any coin c ≤ a |
| Recurrence | ways(n−1) + ways(n−2) | 1 + min of best(a − c) |
| Base case | ways(0) = ways(1) = 1 | best(0) = 0 |
| Fill order | n = 2, 3 … up | a = 1, 2 … up |
Each best[a] reads cells for smaller amounts, which the loop has already filled. Here a cell can read any earlier cell, not just the last two, so the whole list stays.
07 When it goes wrong
@cache
def ways(n):
... # also reads a global STEPS listA key that misses part of the stateThe cache only knows n. Change STEPS and it returns answers for the old one. Everything the answer depends on must be an argument.if memo.get(n):
return memo[n]A stored 0 looks like a miss0 is falsy, so a saved answer of 0 is computed again every time, and the speed-up quietly disappears. Test with n in memo.ways(5000, {})Memoised, but still too deepThe first call still recurses all the way down to 0. In CPython that passes the default recursion limit of 1000 and raises RecursionError, with a dictionary or with @cache. The bottom-up loop has no depth.for i in range(n, 1, -1):
dp[i] = dp[i - 1] + dp[i - 2]Filling in the wrong orderGoing downwards reads cells that are still 0, so the answer is wrong rather than slow. Fill each cell after every cell it reads.Memoisation only helps when calls repeat. Merge sort splits into halves that never overlap, so a memo there just costs memory. Look for the same arguments turning up in different branches first.