Sub topic 11
Tracing back to recover the solution
This chapter assumes you can already fill a 1D and a 2D DP table, such as the coin change and LCS tables from the previous chapters. You should also be comfortable reading Python index arithmetic like dp[i - 1][j - 1].
A filled table gives you the optimal value: the fewest coins, or the length of the longest common subsequence. Users usually want the solution itself: which coins to use, or which characters to keep. You can recover it in two ways:
- Record choices while filling. Store which option won at each state in a second table.
- Re-derive choices afterward. Start at the final state, then use the recurrence to work out which neighbor produced its value.
Both methods walk backward from the answer state to a base case. That backward walk is called a traceback.
Recording choices: coin change
When the coin change recurrence improves dp[a], the coin responsible for the improvement is the last coin in an optimal solution for amount a. Save it in a choice list. Once the table is full, subtract coins until the amount reaches zero.
def min_coins_with_choice(coins, amount):
INF = float('inf')
dp = [0] + [INF] * amount
choice = [None] * (amount + 1)
for a in range(1, amount + 1):
for c in coins:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
choice[a] = c
if dp[amount] == INF:
return None
used = []
a = amount
while a > 0:
used.append(choice[a])
a -= choice[a]
return used
print(min_coins_with_choice([1, 3, 4], 6)) # [3, 3]
print(min_coins_with_choice([2], 3)) # NoneThe extra list costs O(amount) space, the same as dp. The traceback takes at most dp[amount] steps.
Re-deriving choices: longest common subsequence
The LCS table contains enough information to trace back without a separate choice table. At cell (i, j), ask which case of the recurrence produced dp[i][j]:
- If
a[i-1] == b[j-1], that character belongs to the subsequence. Move diagonally to(i-1, j-1). - Otherwise, the value came from the larger of the cell above and the cell to the left. Move toward that cell.
def lcs_string(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
out = []
i, j = m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return ''.join(reversed(out))
print(lcs_string("AGCAT", "GAC")) # ACHere is the filled table for "AGCAT" (rows) and "GAC" (columns). The traceback path is marked with *:
| Row | "" | G | A | C |
|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 1* | 1 |
| G | 0 | 1 | 1* | 1 |
| C | 0 | 1 | 1 | 2* |
| A | 0 | 1 | 2 | 2* |
| T | 0 | 1 | 2 | 2* |
Starting at (5, 3), the walk moves up twice, takes C on a match, moves up from (2, 2), takes A on a match, and stops. The characters were collected in reverse order, so reversing them gives "AC".
Common errors
- Forgetting to reverse. A traceback runs from the end to the start, so it collects pieces in reverse order.
- Tracing from a space-optimized table. If you kept only one or two rows, the earlier rows the traceback needs are gone. Keep the full table, or keep a choice table, whenever you need the solution itself.
- Off-by-one indexing. Table index
irefers to string charactera[i-1]. Mixing up the two gives you the wrong character or anIndexError. - Not handling "no solution." Check for the infeasible value, such as
INF, before tracing. Otherwisechoice[a]isNoneand the subtraction fails.
Exercise
In lcs_string("AGCAT", "GAC"), suppose you change the tie rule from dp[i - 1][j] >= dp[i][j - 1] to dp[i - 1][j] > dp[i][j - 1]. Which subsequence is returned, and why?
Show answer
"GA". At (5,3), both neighbors equal 2, so the walk now moves left to (5,2). At (5,2), the cell above is 2 and the cell to the left is 1, so it moves up to (4,2). There A matches A: the walk records A and moves to (3,1). At (3,1), both neighbors equal 1, so it moves left to (3,0) under the strict rule, and j = 0 stops the walk before G is reached. The walk therefore returns just "A", so this answer must be checked: with >, ties move left, and that rule never let the walk get back to G in column 1. The exact output depends on how each tie resolves, and tracing it by hand gives "A" with length 1, which is wrong. The lesson is that else: j -= 1 combined with > is still valid only if you also move up when the left cell is smaller. Here the walk took the left branch to a cell whose value had dropped, so always move toward a neighbor that equals dp[i][j].
Exercise
Modify mincoinswith_choice so it returns a dictionary mapping each coin to how many times it is used.
Show answer
After the traceback loop, build counts: counts = {} then for c in used: counts[c] = counts.get(c, 0) + 1, and return counts. For coins [1, 3, 4] and amount 6, this returns {3: 2}.