Sub topic 8
Recovering Which Items Were Chosen
This chapter assumes you have read the bottom-up table chapter. You should know that dp[i][c] holds the best value using the first i items with capacity c, and you should be comfortable with nested Python lists.
The filled table tells you the best total value, dp[n][W]. It does not directly tell you which items make up that value. The table does hold enough information to recover them, though. Every cell was set by one of two choices, skip item i or take it, and you can work out which choice was made by comparing neighbouring cells.
The Walk-Back Rule
Start at the bottom-right cell, dp[n][W], and move up one row at a time:
- If
dp[i][c] == dp[i-1][c], skipping itemialready gives this value. Do not take the item, and keep the same capacityc. - Otherwise the value could only come from taking item
i. Record it, then subtract its weight:c -= weights[i-1].
Stop when you reach row 0. Because the walk visits each row once, reconstruction costs O(n) time on top of the O(nW) needed to fill the table.
The Code
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])Tracing the Example
| Row i | c | dp[i][c] | dp[i-1][c] | Decision |
|---|---|---|---|---|
| 3 | 50 | 220 | 160 | take item 2, c becomes 20 |
| 2 | 20 | 100 | 60 | take item 1, c becomes 0 |
| 1 | 0 | 0 | 0 | skip item 0 |
The chosen items are 1 and 2. Their weights are 20 + 30 = 50 and their values are 100 + 120 = 220, which matches the table.
Common Errors
- Forgetting to reduce
c. If you leavecunchanged after taking an item, every later comparison reads the wrong column, and you may report items that do not fit. - Off-by-one indexing. Row
icorresponds to itemi - 1in the input lists. Mixing these up shifts every answer by one item. - Expecting a unique answer. When two subsets tie for the best value, the walk-back returns one of them. Because the rule prefers skipping on a tie, it favours solutions built from earlier items.
- Trying this on a one-dimensional array. The space-saving version in the next chapter overwrites earlier rows, so the comparison with
dp[i-1][c]is no longer possible.
Exercise
Using the same values [60, 100, 120] and weights [10, 20, 30] with capacity 40, the best value is 180. Walk back through the table and list the chosen item indices. (Hints: dp[2][40] = 160, dp[2][10] = 60, dp[1][10] = 60, dp[0][10] = 0.)
Show answer
At row 3 with c = 40, 180 differs from 160, so take item 2 and c becomes 10. At row 2 with c = 10, 60 equals 60, so skip item 1. At row 1 with c = 10, 60 differs from 0, so take item 0 and c becomes 0. The chosen items are [0, 2], with weight 40 and value 180.
Exercise
Why does the walk-back start at dp[n][W] and not at the largest value anywhere in the last row?
Show answer
The last row is non-decreasing in c, so dp[n][W] is already the maximum of that row. Starting there also keeps the capacity bookkeeping consistent, because every subtraction starts from the true capacity W.