Sub topic 10
Top-Down Interval DP with Memoization
This chapter assumes you know recursion, basic memoization, and the split-point recurrence from earlier chapters. You should also be comfortable reading Python decorators such as functools.lru_cache.
The bottom-up tables you have seen so far need a careful loop order: fill by interval length so every smaller range is ready before a larger one reads it. Top-down memoization removes that bookkeeping. You write the recurrence as a recursive function of (i, j), cache each result, and the recursion computes dependencies in whatever order they are needed.
The Same Recurrence, Written Recursively
Here is matrix chain multiplication in top-down form. Matrix i has shape dims[i] x dims[i + 1], and cost(i, j) is the minimum number of scalar multiplications for the inclusive range i..j.
from functools import lru_cache
def matrix_chain_memo(dims):
n = len(dims) - 1
@lru_cache(maxsize=None)
def cost(i, j):
if i == j:
return 0
return min(
cost(i, k) + cost(k + 1, j) + dims[i] * dims[k + 1] * dims[j + 1]
for k in range(i, j)
)
return cost(0, n - 1)
print(matrix_chain_memo([10, 30, 5, 60])) # 4500The code is the recurrence with one base case added. A call on a range of length L recurses only into strictly shorter ranges, so the recursion always reaches i == j and stops. The cache means each (i, j) pair runs its loop once. Every later call returns the stored value.
Why the Cache Matters
Without memoization, the same subranges are solved over and over. The diagram shows the calls for four matrices. Several nodes appear under more than one parent.
With the cache, the work matches the bottom-up version: O(n²) states, each doing O(n) work in its split loop, for O(n³) total.
When to Prefer Top-Down
| Factor | Top-down memo | Bottom-up table |
|---|---|---|
| Loop order | Handled by recursion | You must order by length |
| States visited | Only those reachable from the root | All O(n²) states |
| Overhead | Function calls and hashing | Plain array access |
| Recursion depth | Up to about n frames | None |
| Later optimizations | Harder | Easier (for example, Knuth's optimization) |
Top-down works well while you are still finding the right recurrence, and when many states are never reached. Bottom-up runs faster in Python and leaves you with an explicit table to inspect.
Common Errors
- Missing or wrong base case. If you check
i == jbut a recurrence can also producei > j(as endpoint-shrinking recurrences can), you need a base case for the empty range too. Otherwise you get infinite recursion or amin()of an empty sequence. - Cache defined at module level. If the cached function reads a global
dims, results from one input leak into the next call. Define the cached function inside the outer function, as in the example above, so each call to the outer function gets a fresh cache. - Recursion limit. Depth grows with n. Python's default limit is about 1000, so large inputs may need
sys.setrecursionlimitor a switch to bottom-up. - Reading the cache for reconstruction. To recover the parenthesization, return or store the best
kalong with the cost. Do not re-derive it by callingcostagain without the cache.
Exercise
For a chain of n matrices, how many distinct (i, j) pairs can the cache hold, and why does the recursion never call cost(i, j) with i > j in the matrix chain code?
Show answer
It can hold n(n+1)/2 pairs, one for each i <= j. The split loop uses k in range(i, j), so the left call cost(i, k) has k >= i and the right call cost(k + 1, j) has k + 1 <= j. Both subranges are non-empty.
Exercise
Rewrite longestpalindromicsubsequence top-down. Which base cases do you need?
Show answer
Define best(i, j) with lru_cache. Return 0 when i > j (the empty range, reached when s[i] == s[j] and j == i + 1) and 1 when i == j. Otherwise return best(i + 1, j - 1) + 2 if s[i] == s[j], else max(best(i + 1, j), best(i, j - 1)). Call best(0, len(s) - 1).