Tabulation
Tabulation is the bottom-up way of doing dynamic programming. Instead of starting from the big problem and recursing down (memoization), you start from the smallest subproblems and fill a table with loops, in an order where everything an entry needs has already been computed. The answer is the last entry you fill.
| Memoization (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| Structure | recursion + cache | loops + table |
| Computes | only the subproblems that are actually needed | every subproblem in the table |
| Recursion limit | can be a problem | no recursion at all |
| Memory tricks | hard | easy (often keep only the last row) |
Fibonacci, bottom-up
def fib_table(n):
table = [0] * (n + 1)
if n >= 1:
table[1] = 1
for i in range(2, n + 1):
table[i] = table[i - 1] + table[i - 2] # both already filled
return table
t = fib_table(12)
print(t)
print("fib(12) =", t[12])[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
fib(12) = 144
Each entry only needs the two before it, so we can throw the rest of the table away and keep just two variables: O(n) time, O(1) memory.
def fib(n):
prev, cur = 0, 1
for _ in range(n):
prev, cur = cur, prev + cur
return prev
print(fib(12), fib(90))
print(len(str(fib(5000))), "digits in fib(5000)") # far too deep for plain recursion144 2880067194370816120
1045 digits in fib(5000)
Coin change: fewest coins
Given coin values and an amount, what is the smallest number of coins that add up to the amount? Let best[a] be the fewest coins for amount a. Then best[0] = 0, and for every coin c ≤ a:
best[a] = min over coins c of best[a - c] + 1Filling a = 1, 2, 3, … guarantees best[a - c] is ready when needed:
def min_coins(coins, amount):
INF = float("inf")
best = [0] + [INF] * amount
used = [None] * (amount + 1)
for a in range(1, amount + 1):
for c in coins:
if c <= a and best[a - c] + 1 < best[a]:
best[a] = best[a - c] + 1
used[a] = c
if best[amount] == INF:
return None
combo, a = [], amount
while a > 0:
combo.append(used[a])
a -= used[a]
return best[amount], combo
coins = [1, 4, 6]
print("table:", [min_coins(coins, a)[0] for a in range(13)])
print("amount 8:", min_coins(coins, 8))
print("amount 12:", min_coins(coins, 12))
print([5, 10], "amount 3:", min_coins([5, 10], 3))table: [0, 1, 2, 3, 1, 2, 1, 2, 2, 3, 2, 3, 2]
amount 8: (2, [4, 4])
amount 12: (2, [6, 6])
[5, 10] amount 3: None
With coins 1, 4 and 6, the greedy approach ("take the biggest coin that fits") would pay 8 as 6 + 1 + 1, three coins; the table finds 4 + 4.
Longest common subsequence
The longest common subsequence (LCS) of two strings is the longest sequence of characters that appears in both, in order, but not necessarily next to each other. It is the core of diff tools and DNA comparison. Let L[i][j] be the LCS length of the first i characters of a and the first j of b:
if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1
else: L[i][j] = max(L[i-1][j], L[i][j-1])def lcs(a, b):
L = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
# walk back from the bottom-right corner to recover the letters
out, i, j = [], len(a), len(b)
while i and j:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1]); i -= 1; j -= 1
elif L[i - 1][j] >= L[i][j - 1]:
i -= 1
else:
j -= 1
return L, "".join(reversed(out))
a, b = "STONE", "TONGUE"
L, common = lcs(a, b)
print(" " + " ".join(" " + b))
for i, row in enumerate(L):
print((" " + a)[i], " ", " ".join(map(str, row)))
print("LCS:", common, "length", L[-1][-1]) T O N G U E
0 0 0 0 0 0 0
S 0 0 0 0 0 0 0
T 0 1 1 1 1 1 1
O 0 1 2 2 2 2 2
N 0 1 2 3 3 3 3
E 0 1 2 3 3 3 4
LCS: TONE length 4
How to design a table
- Define the entry in words: "
best[a]= fewest coins for amounta". - Write the recurrence: how an entry follows from smaller ones.
- Set the base cases:
best[0] = 0, row 0 and column 0 of the LCS table. - Choose the fill order so dependencies come first (increasing
a; row by row). - Read the answer (and, if needed, walk back through the table to rebuild the solution).
Test yourself
What is the main difference between tabulation and memoization?
- Tabulation is always slower
- Tabulation fills a table bottom-up with loops; memoization caches results of top-down recursion
- Memoization doesn't use memory
- Only tabulation gives correct answers
With coins [1, 4, 6], what is the fewest number of coins for amount 8?
- 2
- 3
- 4
- 8
Why must the coin change table be filled in increasing order of amount?
- To save memory
- Each entry depends on entries for smaller amounts
- Python lists only grow forwards
- It doesn't matter