Sub topic 8
Recovering Which Items Were Chosen
The bottom-up table from the previous chapter gives the best total value. For the running example that value is 220. A packing list needs more than that number: it needs to say which items go in the bag. This chapter shows how to read that list back out of the finished table, what can go wrong while doing so, and what to keep in memory if you want the list without storing the whole table.
This chapter assumes you have read the chapter on the bottom-up DP table and are comfortable with this definition:
dp[i][c]is the best value you can get using only the firstiitems (indices0toi - 1) with capacityc.- Row
0is all zeros, and the answer sits indp[n][W].
The Key Observation
Every cell dp[i][c] was filled by choosing between two options:
- Skip item
i - 1. The value isdp[i - 1][c]. - Take item
i - 1if it fits. The value isdp[i - 1][c - w] + v.
If dp[i][c] differs from dp[i - 1][c], skipping could not have produced it, so item i - 1 must have been taken. If the two cells are equal, skipping gives an optimal answer and we can leave the item out.
That gives a backward walk. Start at (n, W). At each row, compare the cell with the one directly above it. If they differ, record the item and move left by its weight. Then move up one row either way. Stop when you reach row 0.
The Implementation
Here is the full table builder with reconstruction added at the end:
def knapsack_table(values, weights, capacity):
n = len(values)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
v, w = values[i - 1], weights[i - 1]
for c in range(capacity + 1):
dp[i][c] = dp[i - 1][c]
if w <= c and dp[i - 1][c - w] + v > dp[i][c]:
dp[i][c] = dp[i - 1][c - w] + v
chosen = []
c = capacity
for i in range(n, 0, -1):
if dp[i][c] != dp[i - 1][c]:
chosen.append(i - 1)
c -= weights[i - 1]
chosen.reverse()
return dp[n][capacity], chosen
print(knapsack_table([60, 100, 120], [10, 20, 30], 50)) # (220, [1, 2])The walk does one comparison per row, so it costs O(n) on top of the O(nW) needed to fill the table. Reconstruction adds almost nothing to the running time.
Tracing the Example
All weights are multiples of 10, so the table only changes value at capacities 0, 10, 20, 30, 40 and 50. These are the relevant columns:
| Row `i` (items available) | c=0 | c=10 | c=20 | c=30 | c=40 | c=50 |
|---|---|---|---|---|---|---|
| 0 (none) | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 (item 0: v60, w10) | 0 | 60 | 60 | 60 | 60 | 60 |
| 2 (+ item 1: v100, w20) | 0 | 60 | 100 | 160 | 160 | 160 |
| 3 (+ item 2: v120, w30) | 0 | 60 | 100 | 160 | 180 | 220 |
The walk visits these cells:
| Step | Cell | Compare with | Decision | New `c` |
|---|---|---|---|---|
| 1 | `dp[3][50] = 220` | `dp[2][50] = 160` | take item 2 | 50 − 30 = 20 |
| 2 | `dp[2][20] = 100` | `dp[1][20] = 60` | take item 1 | 20 − 20 = 0 |
| 3 | `dp[1][0] = 0` | `dp[0][0] = 0` | skip item 0 | 0 |
The chosen items are [1, 2], with weight 20 + 30 = 50 and value 100 + 120 = 220, which matches dp[3][50].
def check(values, weights, capacity, best, chosen):
assert len(set(chosen)) == len(chosen), "item used twice"
assert sum(weights[i] for i in chosen) <= capacity, "overweight"
assert sum(values[i] for i in chosen) == best, "value mismatch"
vals, wts, cap = [60, 100, 120], [10, 20, 30], 50
best, chosen = knapsack_table(vals, wts, cap)
check(vals, wts, cap, best, chosen)
print("ok") # okTies and Multiple Optimal Answers
An instance can have more than one optimal set. Take two identical items, each with value 10 and weight 5, and capacity 5. Either item alone is optimal. At dp[2][5], the cell equals dp[1][5], so the walk skips item 1 and then takes item 0. The answer is [0].
The rule "equal means skip" prefers earlier items. You can make the walk prefer taking instead, by testing whether the take option reproduces the cell value:
def reconstruct_prefer_take(dp, values, weights, capacity):
chosen = []
c = capacity
for i in range(len(values), 0, -1):
v, w = values[i - 1], weights[i - 1]
if w <= c and dp[i][c] == dp[i - 1][c - w] + v:
chosen.append(i - 1)
c -= w
chosen.reverse()
return chosen
values, weights, capacity = [10, 10], [5, 5], 5
n = len(values)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
v, w = values[i - 1], weights[i - 1]
for c in range(capacity + 1):
dp[i][c] = dp[i - 1][c]
if w <= c:
dp[i][c] = max(dp[i][c], dp[i - 1][c - w] + v)
print(reconstruct_prefer_take(dp, values, weights, capacity)) # [1]Both rules give a valid optimal set, because each step moves to a cell that holds the best value for the remaining subproblem. Choose the rule deliberately when the result matters. Examples are tests that compare against a fixed expected list, or cases where one optimal set is cheaper in some secondary sense, such as using fewer items.
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Treating row `i` as item `i` | Wrong items, or `IndexError` on the last row | Row `i` decides item `i - 1` |
| Starting the walk at `dp[n][W]` but forgetting to update `c` | The same column is compared on every row, giving extra items | Subtract the weight after each take |
| Starting at a column other than `W` | A valid but smaller set | Start at the cell that holds the answer |
| Forgetting to reverse | Items listed last to first | Reverse, or insert at the front |
| Reconstructing from a single reused array | Nonsense, because earlier rows were overwritten | Keep decisions separately (next section) |
Keeping Only the Decisions
The walk needs to know, for each row and column, whether the item was taken. It does not need the values themselves. That lets you keep a compact boolean table keep[i][c] while keeping only one row of values. The next chapter explains why the capacity loop below runs backwards. For now, note that keep records exactly the strict-improvement decision that the 2D version tests.
def knapsack_with_keep(values, weights, capacity):
n = len(values)
dp = [0] * (capacity + 1)
keep = [[False] * (capacity + 1) for _ in range(n)]
for i, (v, w) in enumerate(zip(values, weights)):
for c in range(capacity, w - 1, -1):
if dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
keep[i][c] = True
chosen = []
c = capacity
for i in range(n - 1, -1, -1):
if keep[i][c]:
chosen.append(i)
c -= weights[i]
chosen.reverse()
return dp[capacity], chosen
print(knapsack_with_keep([60, 100, 120], [10, 20, 30], 50)) # (220, [1, 2])The memory is still proportional to n × W, but each entry is one flag instead of a full integer. With a bit array you can pack eight flags into a byte. If even that is too large, divide-and-conquer methods such as Hirschberg-style splitting can recover the set in O(W) extra space, at the cost of roughly doubling the running time.
Exercise
For values [60, 100, 120], weights [10, 20, 30] and capacity 40, use the table in this chapter to trace the backward walk. Which items are chosen?
Show answer
Start at dp[3][40] = 180 and compare it with dp[2][40] = 160. They differ, so take item 2 and set c = 10. At dp[2][10] = 60, the cell above is dp[1][10] = 60. They are equal, so skip item 1. At dp[1][10] = 60, the cell above is dp[0][10] = 0, so take item 0 and set c = 0. The chosen items are [0, 2], with weight 40 and value 180.
Exercise
A colleague fills the table correctly but writes the walk as if dp[i][c] != dp[i - 1][c]: chosen.append(i) and keeps c -= weights[i - 1]. What goes wrong on the running example?
Show answer
The weight bookkeeping is correct, but every recorded index is one too high. The walk returns [2, 3] instead of [1, 2], and index 3 does not exist in a three-item list. Row i decides item i - 1, so the append must use i - 1.
Exercise
Why does reconstruction with a single reused value array fail, while the keep table works?
Show answer
The single array is overwritten in place, so after the loop it holds only the last row. The walk needs to compare row i with row i - 1 at shifting columns, and those earlier rows no longer exist. The keep table stores each row's take-or-skip decision before it is overwritten, which is all the walk needs.