Mini Project: A DP Solver That Shows Its Work
Every dynamic program in this course had the same three parts: a set of subproblems in a valid evaluation order, a recurrence that computes each subproblem's value and records the choice that achieved it, and a walk back through the choices that reconstructs the answer. In this project you write those three parts once, as a small generic solver, and then plug in four problems from the course: LCS, edit distance, 0/1 knapsack and matrix-chain multiplication. For each one the solver prints the filled table with the reconstruction path marked, and the reconstructed answer. A final step checks every answer against brute force on random instances.
Each step is a complete program; later steps repeat the pieces they need, so you can run any of them on its own.
Step 1: The solver and the table printer
The solver takes the subproblems as a list in evaluation order (so it is the bottom-up method of Bottom-Up Dynamic Programming), and a function recur(state, value) that returns a pair (best value, choice) using only values of earlier states. The choice is anything the problem needs for reconstruction. The printer shows a two-dimensional table, marking chosen cells with *.
As a first test, rod cutting: one-dimensional, state = rod length, choice = first piece.
def solve(states, recur):
"""bottom-up DP: states in a valid order; recur(s, value) -> (value, choice)"""
value, choice = {}, {}
for s in states:
value[s], choice[s] = recur(s, value)
return value, choice
def show(row_labels, col_labels, cell, marked=(), width=4):
"""print a 2-D table; cell(i, j) -> value or None (blank); marked cells get a *"""
print(" " * 6 + "".join(f"{c:>{width}}" for c in col_labels))
for i, r in enumerate(row_labels):
cells = []
for j in range(len(col_labels)):
text = cell(i, j)
cells.append(" " * width if text is None else f"{str(text) + ('*' if (i, j) in marked else ' '):>{width}}")
print(f"{r:>5} " + "".join(cells).rstrip())
prices = [2, 6, 9, 11, 15, 19, 20, 24]
n = len(prices)
def rod(j, value):
if j == 0:
return 0, None
return max((prices[i - 1] + value[j - i], i) for i in range(1, j + 1))
value, choice = solve(range(n + 1), rod)
pieces, j = [], n
while j > 0:
pieces.append(choice[j]); j -= choice[j]
path = set()
j = n
while j > 0:
path.add((0, j)); j -= choice[j]
show(["r[j]", "s[j]"], list(range(n + 1)),
lambda i, j: value[j] if i == 0 else choice[j], marked=path)
print("best revenue", value[n], "with pieces", pieces) 0 1 2 3 4 5 6 7 8
r[j] 0 2 6* 9 12 15 19 21 25*
s[j] 1 2 3 2 5 6 6 6
best revenue 25 with pieces [6, 2]
The max over pairs (value, i) breaks ties by the larger first piece, unlike the lessons, which kept the smallest. That is why length 8 is cut here as instead of : an equally optimal answer. Tie rules decide which optimal solution is reconstructed, and the remaining steps choose them to agree with the animations.
Step 2: Longest common subsequence
States are pairs of prefix lengths in row-major order; the choice records which neighbour the value came from ("diag" for a match, "up" or "left"). The walk back follows the choices from the corner, and those cells are marked. The tie rule (up before left) is the one of the LCS animation.
def solve(states, recur):
value, choice = {}, {}
for s in states:
value[s], choice[s] = recur(s, value)
return value, choice
def show(row_labels, col_labels, cell, marked=(), width=4):
print(" " * 6 + "".join(f"{c:>{width}}" for c in col_labels))
for i, r in enumerate(row_labels):
cells = []
for j in range(len(col_labels)):
text = cell(i, j)
cells.append(" " * width if text is None else f"{str(text) + ('*' if (i, j) in marked else ' '):>{width}}")
print(f"{r:>5} " + "".join(cells).rstrip())
def lcs_solver(x, y):
m, n = len(x), len(y)
def recur(s, V):
i, j = s
if i == 0 or j == 0:
return 0, None
if x[i - 1] == y[j - 1]:
return V[i - 1, j - 1] + 1, "diag"
return (V[i - 1, j], "up") if V[i - 1, j] >= V[i, j - 1] else (V[i, j - 1], "left")
states = [(i, j) for i in range(m + 1) for j in range(n + 1)]
V, C = solve(states, recur)
i, j, path, out = m, n, set(), []
while C[i, j] is not None:
path.add((i, j))
if C[i, j] == "diag":
out.append(x[i - 1]); i, j = i - 1, j - 1
elif C[i, j] == "up":
i -= 1
else:
j -= 1
show([""] + list(x), [""] + list(y), lambda a, b: V[a, b], path)
return "".join(reversed(out))
print("LCS:", lcs_solver("ALGORITHM", "LOGARITHM"))
print()
print("LCS:", lcs_solver("DYNAMIC", "DIAGRAM")) L O G A R I T H M
0 0 0 0 0 0 0 0 0 0
A 0 0 0 0 1 1 1 1 1 1
L 0 1* 1* 1 1 1 1 1 1 1
G 0 1 1 2* 2* 2 2 2 2 2
O 0 1 2 2 2* 2 2 2 2 2
R 0 1 2 2 2 3* 3 3 3 3
I 0 1 2 2 2 3 4* 4 4 4
T 0 1 2 2 2 3 4 5* 5 5
H 0 1 2 2 2 3 4 5 6* 6
M 0 1 2 2 2 3 4 5 6 7*
LCS: LGRITHM
D I A G R A M
0 0 0 0 0 0 0 0
D 0 1* 1* 1* 1* 1* 1 1
Y 0 1 1 1 1 1* 1 1
N 0 1 1 1 1 1* 1 1
A 0 1 1 2 2 2 2* 2
M 0 1 1 2 2 2 2 3*
I 0 1 2 2 2 2 2 3*
C 0 1 2 2 2 2 2 3*
LCS: DAM
The starred cells are exactly the "done" cells of the animation's last frame: the reconstruction path from the corner. On a diagonal step the solver collects a letter, so LGRITHM and DAM can be read off the starred cells where the row and column letters agree.
Step 3: Edit distance with an alignment
The same solver with the edit-distance recurrence. The choice is the operation, and the walk back produces an alignment: the two strings written one above the other with gaps, plus a line of markers (| match, x substitution, - deletion, + insertion).
def solve(states, recur):
value, choice = {}, {}
for s in states:
value[s], choice[s] = recur(s, value)
return value, choice
def show(row_labels, col_labels, cell, marked=(), width=4):
print(" " * 6 + "".join(f"{c:>{width}}" for c in col_labels))
for i, r in enumerate(row_labels):
cells = []
for j in range(len(col_labels)):
text = cell(i, j)
cells.append(" " * width if text is None else f"{str(text) + ('*' if (i, j) in marked else ' '):>{width}}")
print(f"{r:>5} " + "".join(cells).rstrip())
def edit_solver(x, y):
m, n = len(x), len(y)
def recur(s, V):
i, j = s
if i == 0:
return j, "ins" if j else None
if j == 0:
return i, "del"
options = [(V[i - 1, j - 1] + (x[i - 1] != y[j - 1]), "sub" if x[i - 1] != y[j - 1] else "keep"),
(V[i - 1, j] + 1, "del"), (V[i, j - 1] + 1, "ins")]
return min(options, key=lambda t: t[0]) # first minimum: diagonal, then delete, then insert
V, C = solve([(i, j) for i in range(m + 1) for j in range(n + 1)], recur)
i, j, path, top, mid, bottom = m, n, {(m, n)}, [], [], []
while C[i, j] is not None:
op = C[i, j]
if op in ("keep", "sub"):
top.append(x[i - 1]); bottom.append(y[j - 1]); mid.append("|" if op == "keep" else "x"); i, j = i - 1, j - 1
elif op == "del":
top.append(x[i - 1]); bottom.append(" "); mid.append("-"); i -= 1
else:
top.append(" "); bottom.append(y[j - 1]); mid.append("+"); j -= 1
path.add((i, j))
show([""] + list(x), [""] + list(y), lambda a, b: V[a, b], path)
print("distance", V[m, n])
for line in (top, mid, bottom):
print((" " + " ".join(reversed(line))).rstrip())
edit_solver("TRACE", "CRATER")
print()
edit_solver("PARK", "SPARE") C R A T E R
0* 1 2 3 4 5 6
T 1 1* 2 3 3 4 5
R 2 2 1* 2 3 4 4
A 3 3 2 1* 2 3 4
C 4 3 3 2 2* 3 4
E 5 4 4 3 3 2* 3*
distance 3
T R A C E
x | | x | +
C R A T E R
S P A R E
0* 1* 2 3 4 5
P 1 1 1* 2 3 4
A 2 2 2 1* 2 3
R 3 3 3 2 1* 2
K 4 4 4 3 2 2*
distance 2
P A R K
+ | | | x
S P A R E
The first table is the one of the edit-distance animation, and the alignment shows its edits: T and C substituted, R, A, E kept, R inserted. The starred cells include the start cell , where every walk ends.
Step 4: Knapsack and matrix chains
Two different table shapes with the same solver. For the 0/1 knapsack the states are (items considered, capacity) and the choice is "take" or "skip". For matrix chains the states are subchains in order of increasing length, the choice is the split , and reconstruction is a recursion instead of a walk, because each split leaves two subproblems.
def solve(states, recur):
value, choice = {}, {}
for s in states:
value[s], choice[s] = recur(s, value)
return value, choice
def show(row_labels, col_labels, cell, marked=(), width=4):
print(" " * 6 + "".join(f"{c:>{width}}" for c in col_labels))
for i, r in enumerate(row_labels):
cells = []
for j in range(len(col_labels)):
text = cell(i, j)
cells.append(" " * width if text is None else f"{str(text) + ('*' if (i, j) in marked else ' '):>{width}}")
print(f"{r:>5} " + "".join(cells).rstrip())
def knapsack_solver(weights, values, W):
n = len(weights)
def recur(s, V):
i, c = s
if i == 0:
return 0, None
skip = V[i - 1, c]
if weights[i - 1] <= c and V[i - 1, c - weights[i - 1]] + values[i - 1] > skip:
return V[i - 1, c - weights[i - 1]] + values[i - 1], "take"
return skip, "skip"
V, C = solve([(i, c) for i in range(n + 1) for c in range(W + 1)], recur)
taken, c, path = [], W, set()
for i in range(n, 0, -1):
path.add((i, c))
if C[i, c] == "take":
taken.append(i); c -= weights[i - 1]
show(["0"] + [f"#{i}" for i in range(1, n + 1)], list(range(W + 1)), lambda a, b: V[a, b], path)
print("best value", V[n, W], "taking items", sorted(taken))
def chain_solver(p):
n = len(p) - 1
def recur(s, V):
i, j = s
if i == j:
return 0, None
return min((V[i, k] + V[k + 1, j] + p[i - 1] * p[k] * p[j], k) for k in range(i, j))
states = [(i, i + L - 1) for L in range(1, n + 1) for i in range(1, n - L + 2)]
V, C = solve(states, recur)
def parens(i, j):
return f"A{i}" if i == j else "(" + parens(i, C[i, j]) + parens(C[i, j] + 1, j) + ")"
show([f"A{i}" for i in range(1, n + 1)], [f"A{j}" for j in range(1, n + 1)],
lambda a, b: V[a + 1, b + 1] if a <= b else None, {(0, n - 1)}, width=6)
print("best order", parens(1, n), "with", V[1, n], "multiplications")
knapsack_solver([4, 3, 2, 5], [10, 7, 4, 12], 10)
print()
chain_solver([12, 4, 10, 3, 8, 5]) 0 1 2 3 4 5 6 7 8 9 10
0 0 0 0 0 0 0 0 0 0 0 0
#1 0* 0 0 0 10 10 10 10 10 10 10
#2 0 0 0 7* 10 10 10 17 17 17 17
#3 0 0 4 7 10 11* 14 17 17 21 21
#4 0 0 4 7 10 12 14 17 19 22 23*
best value 23 taking items [2, 3, 4]
A1 A2 A3 A4 A5
A1 0 480 264 552 540*
A2 0 120 216 300
A3 0 240 270
A4 0 120
A5 0
best order (A1((A2A3)(A4A5))) with 540 multiplications
Both tables match the lessons' animations. In the matrix-chain solver, min over pairs (cost, k) breaks ties by the smaller , the same rule as the animation's strict <. Notice how little each problem needed: a list of states in a valid order, a recurrence returning (value, choice), and a reconstruction.
Step 5: Checking against brute force
A solver is only as good as its recurrences. The last step runs all four problems (without printing tables) against independent brute-force solutions on random small instances: every subsequence for LCS, a direct recursion for edit distance, every subset for knapsack, every parenthesization for matrix chains.
import random
from functools import cache
from itertools import combinations
def solve(states, recur):
value, choice = {}, {}
for s in states:
value[s], choice[s] = recur(s, value)
return value, choice
def lcs_dp(x, y):
def recur(s, V):
i, j = s
if i == 0 or j == 0: return 0, None
if x[i - 1] == y[j - 1]: return V[i - 1, j - 1] + 1, "diag"
return max(V[i - 1, j], V[i, j - 1]), None
V, _ = solve([(i, j) for i in range(len(x) + 1) for j in range(len(y) + 1)], recur)
return V[len(x), len(y)]
def edit_dp(x, y):
def recur(s, V):
i, j = s
if i == 0 or j == 0: return i + j, None
return min(V[i - 1, j - 1] + (x[i - 1] != y[j - 1]), V[i - 1, j] + 1, V[i, j - 1] + 1), None
V, _ = solve([(i, j) for i in range(len(x) + 1) for j in range(len(y) + 1)], recur)
return V[len(x), len(y)]
def knap_dp(w, v, W):
def recur(s, V):
i, c = s
if i == 0: return 0, None
best = V[i - 1, c]
if w[i - 1] <= c: best = max(best, V[i - 1, c - w[i - 1]] + v[i - 1])
return best, None
V, _ = solve([(i, c) for i in range(len(w) + 1) for c in range(W + 1)], recur)
return V[len(w), W]
def chain_dp(p):
n = len(p) - 1
def recur(s, V):
i, j = s
if i == j: return 0, None
return min(V[i, k] + V[k + 1, j] + p[i - 1] * p[k] * p[j] for k in range(i, j)), None
V, _ = solve([(i, i + L - 1) for L in range(1, n + 1) for i in range(1, n - L + 2)], recur)
return V[1, n]
def lcs_brute(x, y):
def is_subseq(s, t):
it = iter(t)
return all(ch in it for ch in s)
return max(k for k in range(len(x) + 1) for c in combinations(x, k) if is_subseq(c, y))
def edit_brute(x, y):
@cache
def d(i, j): # suffix recursion, independent of the table code
if i == len(x) or j == len(y): return len(x) - i + len(y) - j
return min(d(i + 1, j + 1) + (x[i] != y[j]), d(i + 1, j) + 1, d(i, j + 1) + 1)
return d(0, 0)
def knap_brute(w, v, W):
return max(sum(v[i] for i in c) for k in range(len(w) + 1) for c in combinations(range(len(w)), k)
if sum(w[i] for i in c) <= W)
def chain_brute(p):
def orders(i, j):
if i == j: return [0]
return [a + b + p[i - 1] * p[k] * p[j] for k in range(i, j) for a in orders(i, k) for b in orders(k + 1, j)]
return min(orders(1, len(p) - 1))
rng = random.Random(2026)
word = lambda: "".join(rng.choice("ABC") for _ in range(rng.randint(0, 7)))
checks = {"LCS": 0, "edit distance": 0, "knapsack": 0, "matrix chain": 0}
for _ in range(200):
x, y = word(), word()
checks["LCS"] += lcs_dp(x, y) == lcs_brute(x, y)
checks["edit distance"] += edit_dp(x, y) == edit_brute(x, y)
n = rng.randint(0, 6)
w = [rng.randint(1, 9) for _ in range(n)]
v = [rng.randint(0, 20) for _ in range(n)]
W = rng.randint(0, 20)
checks["knapsack"] += knap_dp(w, v, W) == knap_brute(w, v, W)
p = [rng.randint(1, 15) for _ in range(rng.randint(2, 7))]
checks["matrix chain"] += chain_dp(p) == chain_brute(p)
for name, ok in checks.items():
print(f"{name:14}: {ok}/200 random instances agree with brute force")LCS : 200/200 random instances agree with brute force
edit distance : 200/200 random instances agree with brute force
knapsack : 200/200 random instances agree with brute force
matrix chain : 200/200 random instances agree with brute force
All four agree on every instance. A disagreement here would point at the recurrence or the evaluation order, which is the quickest way to debug a new DP before trusting it on large inputs.
Step 6: The core in C++
The same generic idea in C++: a table, a recurrence that returns a value and a choice, and a walk back. To keep it short, the C++ version handles the prefix-pair problems with one function template, parameterised by the recurrence, and prints the LCS and edit-distance tables with their paths.
#include <cstdio>
#include <string>
#include <utility>
#include <vector>
// choice codes: 0 = none, 1 = diagonal, 2 = up, 3 = left
template <class Recur>
void solve_and_show(const std::string& x, const std::string& y, Recur recur, const char* name) {
size_t m = x.size(), n = y.size();
std::vector<std::vector<int>> V(m + 1, std::vector<int>(n + 1)), C = V;
for (size_t i = 0; i <= m; ++i)
for (size_t j = 0; j <= n; ++j) {
auto [value, choice] = recur(V, i, j);
V[i][j] = value; C[i][j] = choice;
}
std::vector<std::vector<bool>> on_path(m + 1, std::vector<bool>(n + 1, false));
for (size_t i = m, j = n; ; ) {
on_path[i][j] = true;
if (C[i][j] == 0) break;
if (C[i][j] == 1) { --i; --j; } else if (C[i][j] == 2) --i; else --j;
}
std::printf("%s of %s and %s: %d\n ", name, x.c_str(), y.c_str(), V[m][n]);
for (size_t j = 0; j < n; ++j) std::printf(" %c", y[j]);
std::printf("\n");
for (size_t i = 0; i <= m; ++i) {
std::string line = std::string(" ") + (i ? x[i - 1] : ' ') + ' ';
for (size_t j = 0; j <= n; ++j) {
char cell[16];
std::snprintf(cell, sizeof cell, "%3d%c", V[i][j], on_path[i][j] ? '*' : ' ');
line += cell;
}
while (!line.empty() && line.back() == ' ') line.pop_back();
std::printf("%s\n", line.c_str());
}
}
int main() {
std::string a = "TRACE", b = "CRATER";
solve_and_show(a, b, [&](const auto& V, size_t i, size_t j) -> std::pair<int, int> {
if (i == 0 || j == 0) return {0, 0};
if (a[i - 1] == b[j - 1]) return {V[i - 1][j - 1] + 1, 1};
return V[i - 1][j] >= V[i][j - 1] ? std::pair{V[i - 1][j], 2} : std::pair{V[i][j - 1], 3};
}, "LCS");
solve_and_show(a, b, [&](const auto& V, size_t i, size_t j) -> std::pair<int, int> {
if (i == 0 && j == 0) return {0, 0};
if (i == 0) return {static_cast<int>(j), 3};
if (j == 0) return {static_cast<int>(i), 2};
int diag = V[i - 1][j - 1] + (a[i - 1] != b[j - 1]), up = V[i - 1][j] + 1, left = V[i][j - 1] + 1;
if (diag <= up && diag <= left) return {diag, 1};
return up <= left ? std::pair{up, 2} : std::pair{left, 3};
}, "edit distance");
}LCS of TRACE and CRATER: 3
C R A T E R
0 0* 0 0 0 0 0
T 0 0* 0 0 1 1 1
R 0 0 1* 1 1 1 2
A 0 0 1 2* 2* 2 2
C 0 1 1 2 2* 2 2
E 0 1 1 2 2 3* 3*
edit distance of TRACE and CRATER: 3
C R A T E R
0* 1 2 3 4 5 6
T 1 1* 2 3 3 4 5
R 2 2 1* 2 3 4 4
A 3 3 2 1* 2 3 4
C 4 3 3 2 2* 3 4
E 5 4 4 3 3 2* 3*
The edit-distance table and path agree with Step 3. The two walks end differently: for LCS the border cells have no choice, so the walk stops at the first border cell it reaches (here , marked); for edit distance the border cells record deletions and insertions, so the walk always runs to .
Ideas to extend the solver
- Memoized mode: add a
solve_top_down(start, recur)that computes values on demand with a cache, and compare how many states each mode touches for a sparse problem (rod cutting with only a few allowed piece lengths). - More problems: optimal BST (interval states like matrix chains, with the root as the choice), weighted interval scheduling (one-dimensional, choice "take" or "skip"), longest increasing subsequence with the state.
- All optimal solutions: let
recurreturn every choice that attains the optimum, and count or list the optimal solutions, as in Reconstructing an Optimal Solution. - Space saving: for the prefix-pair problems, keep only two rows of values and recover the answer with Hirschberg's divide and conquer.
Test yourself
What three ingredients does the generic solver need for each problem?
- A heap, a hash table and a sort
- States in a valid evaluation order, a recurrence returning a value and a choice, and a reconstruction
- A greedy rule, an exchange argument and a potential function
- Only the recurrence
Why is the matrix-chain answer reconstructed by recursion rather than by a single walk back?
- Because its table is not square
- Because each split leaves two subproblems, so the choices form a tree, not a path
- Because recursion is faster
- Because its tie rule is different
Rod cutting in Step 1 prints for length 8, the lessons print . Which is right?
- Only
- Only
- Both: they are different optimal solutions selected by different tie rules
- Neither