AdvancedDynamic Programming

Memoization: recursion that remembers

Write the natural first, then cache each result. time often drops to polynomial with one decorator.

The idea

Many recursive solutions recompute the same inputs again and again. recursion calls fib(3) many times inside fib(6). Storing each answer the first time turns repeated calls into lookups.

(memo) is often easier to get right than tables: write the recursion, add a cache, done.

Worked example

Coin Change: fewest coins for 11 with coins [1, 2, 5]

  1. best(11) = 1 + min(best(10), best(9), best(6))
  2. Without a cache, best(5) is recomputed many times; with one, each amount 0..11 is solved once.
  3. Answer 3 (5 + 5 + 1).

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

memo ← empty map
ways(n):
if n ≤ 1: return 1
if n isn't in memo:
memo[n] ← ways(n − 1) + ways(n − 2)(computed once)
return memo[n]

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

ways(5), 1 or 2 steps at a time

memo

{ } empty — nothing seen yet

Solution · Python

from functools import cache
def coin_change(coins, amount):
@cache
def best(rest):
if rest == 0:
return 0
if rest < 0:
return float("inf")
return 1 + min(best(rest - c) for c in coins)
answer = best(amount)
return -1 if answer == float("inf") else answer

Step 1 of 8

ways(n) = ways(n − 1) + ways(n − 2). Plain recursion recomputes the same small cases again and again. A memo stores each answer the first time, so it's never computed twice.

O(amount × coins) time, O(amount) space for the cache.

How to spot it

  • Your recursion has (the same arguments repeat).

Common mistakes

  • Caching on arguments like lists (they aren't hashable).
  • Deep recursion on large inputs: Python's default limit is about 1000 frames.

Practise the ideas first

Practise it

Go further