Sub topic 9
Top-Down Memoization vs Bottom-Up Tabulation
This chapter assumes you can read Python recursion, you know the unique-paths recurrence ways(i, j) = ways(i - 1, j) + ways(i, j - 1), and you know Big-O notation. Every grid DP can be written in two styles. Both compute the same states with the same recurrence, but they differ in who decides the order of work.
The Two Styles
Top-down memoization writes the recurrence as a recursive function and caches each result the first time it is computed. The call stack works out the order for you. A state is evaluated only when some other state asks for it.
Bottom-up tabulation allocates a table and fills it with loops. You choose the fill order, and it must compute every dependency before the cell that uses it.
Here is the top-down version of unique paths:
from functools import lru_cache
def unique_paths(m, n):
@lru_cache(maxsize=None)
def ways(i, j):
if i == 0 or j == 0:
return 1
return ways(i - 1, j) + ways(i, j - 1)
return ways(m - 1, n - 1)
print(unique_paths(3, 7)) # 28And the bottom-up version of the same recurrence:
def unique_paths_tab(m, n):
dp = [[1] * n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m - 1][n - 1]
print(unique_paths_tab(3, 7)) # 28Why the Cache Matters
Without lru_cache, the recursive version recomputes shared subproblems. Both ways(1, 2) and ways(2, 1) call ways(1, 1), and this overlap compounds across the grid. The call count grows like the number of paths itself, which is exponential in m + n. With the cache, each of the m × n states is computed once.
Choosing Between Them
| Concern | Top-down memoization | Bottom-up tabulation |
|---|---|---|
| Fill order | Handled by recursion | You must design it |
| States computed | Only those reachable from the goal | Every cell in the table |
| Recursion depth | Up to `m + n - 2` frames | None |
| Constant overhead | Function calls and hashing | Plain list indexing |
| Rolling-array optimization | Hard to apply | Natural |
Use top-down when the fill order is awkward or unknown, or when many states are never needed. Use bottom-up for large grids, when speed matters, or when you plan to cut memory down to one row.
Common Errors
- Mutable or unhashable arguments.
lru_cacheneeds hashable arguments. Passing the grid as a list of lists raisesTypeError. Capture the grid in a closure, as the example does, or convert it to a tuple of tuples. - Stale caches. If you define the cached function at module level and call it with different grids, old results leak between calls. Defining the function inside the solver gives each call a fresh cache.
- Mismatched base cases. The recursive base case (
i == 0 or j == 0) must match the table's initialization (first row and column set to 1). If they disagree, the two versions return different answers.
Exercise
You remove the @lrucache decorator from uniquepaths and call unique_paths(16, 16). Roughly how many times is ways called compared with the memoized version, and why?
Show answer
The memoized version evaluates at most 16 × 16 = 256 distinct states. Without the cache, every call is re-expanded, so the number of calls grows with the number of paths. That count is C(30, 15) = 155,117,520 paths, which means hundreds of millions of calls. The overlap between subproblems is what makes the cache essential.
Exercise
A problem's grid is 2000 × 2000 and moves go only right or down. Which style would you pick, and what two reasons justify it?
Show answer
Bottom-up tabulation. Top-down would recurse about 4,000 frames deep, which is past Python's default limit. Tabulation also avoids per-call and hashing overhead across 4 million states, and it allows a one-row rolling array to save memory.