Skip to content

From memoised recursion to dynamic programming

Working knowledgeConcept

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.

stairs.py
def ways(n):
if n <= 1:
return 1 # 0 or 1 steps: one way
return ways(n - 1) + ways(n - 2)
print(ways(5)) # 8

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.

Every call ways(5) makes: 15 calls for 6 different values of n
Call tree · plain ways(5)
ways(5)
ways(4)
ways(3)
ways(2)
ways(1)
ways(0)
ways(1)
ways(2)
ways(1)
ways(0)
ways(3)
ways(2)
ways(1)
ways(0)
ways(1)
  • 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.

Plain recursion
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)
With a memo
def ways(n, memo):
if n <= 1:
return 1
if 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.

ways(5) with a memo: one call or one store per step
Step 1 of 14
Calls made · ways(5) with a memo
ways(5)
ways(4)
ways(3)
ways(2)
ways(1)
ways(0)
ways(1)
ways(2)
ways(3)
memo · n → ways(n)
Empty
  • 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.

0 calls 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.

Top-down (memoised recursion)Ask for n, recurse downStart from the question. The calls find their way to the base cases, and the memo stops repeats.
Bottom-up (a table)Fill 0, 1, 2 … nStart from the base cases. A loop fills each cell from cells already filled. No calls, no stack.

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.

stairs_dp.py
def ways(n): # n >= 1
dp = [0] * (n + 1)
dp[0] = dp[1] = 1 # the base cases
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
print(ways(5)) # 8
print(ways(30)) # 1346269
Filling dp for n = 5, one cell per step
Step 1 of 7
dp · dp[i] = ways(i)
0
1
2
3
4
5
  • not filled yet
  • read for this cell
  • just filled
  • filled earlier

dp has one cell per subproblem, 0 to 5. Nothing is filled yet.

– i

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

The same subproblems, two ways to reach them
QuestionMemoised recursionBottom-up table
Who picks the orderThe recursion, as it needs answersYou, smallest first
Subproblems solvedOnly the ones the question reachesEvery cell in the table
Call stackUp to n frames deepNone: it is a loop
Easiest to writeStraight from the recurrenceOnce you know the fill order
Saving memoryHard: the memo keeps everythingEasy: 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.

Whole table · O(n) space
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
Last two cells · O(1)
prev, cur = 1, 1 # ways(0), ways(1)
for _ in range(2, n + 1):
prev, cur = cur, prev + cur
return 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.
The recipe applied to the stairs and to coin change
StepClimbing stairsCoin change (fewest coins)
Staten steps leftamount a left to pay
First moveclimb 1 or 2use any coin c ≤ a
Recurrenceways(n−1) + ways(n−2)1 + min of best(a − c)
Base caseways(0) = ways(1) = 1best(0) = 0
Fill ordern = 2, 3 … upa = 1, 2 … up
coins.py
def coin_change(coins, amount):
INF = float("inf")
best = [0] + [INF] * amount # best[a]: fewest coins for a
for a in range(1, amount + 1):
for c in coins:
if c <= a:
best[a] = min(best[a], best[a - c] + 1)
return best[amount] if best[amount] != INF else -1
print(coin_change([1, 2, 5], 11)) # 3 (5 + 5 + 1)
print(coin_change([2], 3)) # -1 (cannot be paid)

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.

08 Check yourself

Question

Plain ways(30) makes 2,692,537 calls. How many does the memoised version make?

Question

Why does the bottom-up loop for the stairs run i upwards from 2?

Question

A memoised function gives correct answers for n = 5000 in a loop, but crashes when called first with n = 5000. What is the most likely cause?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?