Sub topic 7
Bottom-Up Solution with a DP Table
This chapter assumes you already know the take-or-skip recurrence from the earlier chapter and how memoization caches best(i, c). You should also be comfortable with nested Python lists and Big-O notation.
Memoization solves the problem top-down and fills its cache in whatever order the recursion reaches each state. Tabulation reverses that approach. It fills every state in a fixed order, starting from the smallest subproblems, so each value it needs has already been computed. This removes the recursion depth limit and the overhead of function calls.
The Table and What Each Cell Means
Define dp[i][c] as the best value you can get using only the first i items with capacity c. The table has n + 1 rows and capacity + 1 columns.
- Row 0 means no items are available, so every cell in it is 0.
- Column 0 means zero capacity, so every cell in it is 0.
- For item
i, with weightwand valuev, the recurrence becomes:
dp[i][c] = max(dp[i-1][c], dp[i-1][c-w] + v), where the second option applies only when w <= c.
Every cell reads only from the row above it. This means filling the table row by row, from left to right, is always safe.
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
return dp
dp = knapsack_table([60, 100, 120], [10, 20, 30], 50)
print(dp[3][50]) # 220The function returns the whole table instead of just the answer. The next chapter walks back through this table to find out which items were chosen.
A Worked Table
All the weights in this example are multiples of 10, so the table below shows only the columns at multiples of 10. The columns in between repeat the value to their left.
| Items available | c=0 | c=10 | c=20 | c=30 | c=40 | c=50 |
|---|---|---|---|---|---|---|
| none | 0 | 0 | 0 | 0 | 0 | 0 |
| + (60, 10) | 0 | 60 | 60 | 60 | 60 | 60 |
| + (100, 20) | 0 | 60 | 100 | 160 | 160 | 160 |
| + (120, 30) | 0 | 60 | 100 | 160 | 180 | 220 |
Look at the last cell. Skipping the third item gives 160. Taking it gives dp[2][20] + 120 = 220. The table keeps the larger value, 220.
Cost
The function fills (n + 1) × (capacity + 1) cells, and each cell takes constant work. Time and space are both O(nW), where W is the capacity. A later chapter explains why this running time is called pseudo-polynomial.
Common Errors
- Aliased rows. Writing
[[0] * (W + 1)] * (n + 1)createsn + 1references to the same list. Every row changes together, and the results are wrong without any error being raised. - Off-by-one item index. Row
idescribes itemvalues[i - 1]. If you usevalues[i], you skip the first item and go out of range on the last one. - Reading from the current row. If you write
dp[i][c - w]instead ofdp[i - 1][c - w], itemican be taken more than once. That is the unbounded variant, not 0/1. - Forgetting the skip copy. If you never set
dp[i][c] = dp[i - 1][c], the cells where the item does not fit stay at 0.
Exercise
Using the same three items, what is dp[3][40], and which of the two options produces it?
Show answer
dp[3][40] = 180. Skipping the third item gives dp[2][40] = 160. Taking it gives dp[2][10] + 120 = 60 + 120 = 180, so taking it wins.
Exercise
A student builds the table with dp = [[0] (capacity + 1)] (n + 1). Using the same three items and capacity 50, what is the result, and why?
Show answer
All rows are the same list object. While the function fills row i, it reads values that it has already overwritten in the current pass, so items can be counted more than once. On this input the function returns 300 instead of 220.