Sub topic 2
Top-down DP with memoization
This chapter assumes you can write recursive Python functions, use dictionaries and lists, and read Big-O notation. It also assumes you already have a recurrence, such as fib(n) = fib(n-1) + fib(n-2) with base cases fib(0) = 0 and fib(1) = 1.
Memoization: cache each subproblem once
Memoization keeps the recursive code and stores each result the first time it is computed. Later calls with the same state return the stored value without recursing again.
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(80)) # 23416728348467685maxsize=None makes the cache unbounded. A bounded cache can evict entries, and evicted subproblems get recomputed. The arguments must be hashable, so pass tuples, not lists.
Tabulation: fill a table bottom-up
Tabulation computes the same recurrence with no recursion. You start at the base cases and fill the table in an order where every entry's dependencies are already filled.
def fib(n):
if n < 2:
return n
table = [0] * (n + 1)
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2]
return table[n]
print(fib(80)) # 23416728348467685The most common bug in tabulation is a wrong fill order, where you read an entry before it has been written.
Counting states and work per state
The cost of a DP solution is:
- Time = number of states × work per state
- Space = number of stored states, plus recursion stack for memoization
Fibonacci has n + 1 states with O(1) work each, so it runs in O(n) time and O(n) space. A problem with m × n states and O(k) work per state takes O(m·n·k) time.
Memoization or tabulation: making the choice
| Factor | Memoization | Tabulation |
|---|---|---|
| States computed | Only those reachable from the query | All states in the table |
| Recursion depth | Can hit Python's limit (about 1000) | None |
| Overhead | Function calls and hashing | Plain array indexing |
| Fill order | Handled by the recursion | You must work it out |
| Memory reduction | Hard | Easy to keep only the rows you need |
Exercise
The memoized fib above raises RecursionError for fib(5000) on a fresh cache. Why, and what are two ways to fix it?
Show answer
The first call recurses about 5000 levels deep before any value is cached, which exceeds Python's default recursion limit of about 1000. You can switch to the tabulated version, which uses no recursion. Or you can warm the cache in increasing order, for example for i in range(5001): fib(i), so that each call only recurses one or two levels.
Exercise
A DP has states (i, j) with 0 ≤ i < 100 and 0 ≤ j < 200, and each state loops over 50 choices. Estimate the total work.
Show answer
100 × 200 = 20,000 states, times 50 operations per state, is about 1,000,000 operations, or O(m·n·k).