Sub topic 7
Bottom-Up Solution with a DP Table
This chapter assumes you know the 0/1 recurrence from the "Take It or Leave It" chapter, the memoized version from the previous chapter, and how nested lists work in Python. Here we compute the same values without recursion. We fill a two-dimensional table in an order that guarantees every value we need is already computed.
The Table and What Each Cell Means
Let n be the number of items and W the capacity. Build a table dp with n + 1 rows and W + 1 columns:
dp[i][c]is the best total value using only the firstiitems (items0toi - 1) with a knapsack of capacityc.- Row
0means "no items available", so every cell in it is0. - Column
0means "zero capacity". With positive weights, nothing fits, so those cells are also0.
The recurrence becomes a rule for filling one cell, where item i - 1 has value v and weight w:
- Skip it:
dp[i - 1][c]. - Take it, allowed only if
w <= c:dp[i - 1][c - w] + v. dp[i][c]is the larger of the two.
The answer is in the bottom-right cell, dp[n][W].
Why the Fill Order Works
Every cell in row i reads only from row i - 1. If you finish each row before you start the next, the inputs are always ready. Inside a row, the column order does not matter for the 2D table, because no cell reads from its own row. That will change when we squeeze the table into one array in a later chapter.
Compare this with memoization. The top-down version computes only the states that recursion actually reaches. The bottom-up version computes all (n + 1) × (W + 1) states, including some the answer never uses. In exchange you get:
- No recursion, so Python's default recursion limit of about 1000 frames never comes into play, however many items there are.
- No hashing overhead from a cache. Plain list indexing is faster per state.
- Predictable memory use and an easy-to-inspect 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] # skip
if w <= c and dp[i - 1][c - w] + v > dp[i][c]:
dp[i][c] = dp[i - 1][c - w] + v # take
return dp
values = [60, 100, 120]
weights = [10, 20, 30]
dp = knapsack_table(values, weights, 50)
print(dp[-1][50]) # 220
for i, row in enumerate(dp):
print(i, row[::10]) # capacities 0, 10, 20, 30, 40, 50Output:
220
0 [0, 0, 0, 0, 0, 0]
1 [0, 60, 60, 60, 60, 60]
2 [0, 60, 100, 160, 160, 160]
3 [0, 60, 100, 160, 180, 220]The function returns the whole table, not only the answer. The next chapter walks back through this table to recover which items were chosen.
Tracing the Example
All weights are multiples of 10, so values only change at multiples of 10. That lets us show just six columns.
| Row (items available) | c=0 | c=10 | c=20 | c=30 | c=40 | c=50 |
|---|---|---|---|---|---|---|
| 0: none | 0 | 0 | 0 | 0 | 0 | 0 |
| 1: + (60, 10) | 0 | 60 | 60 | 60 | 60 | 60 |
| 2: + (100, 20) | 0 | 60 | 100 | 160 | 160 | 160 |
| 3: + (120, 30) | 0 | 60 | 100 | 160 | 180 | 220 |
Three cells in row 3 are worth checking by hand:
dp[3][30]: skip givesdp[2][30] = 160. Take givesdp[2][0] + 120 = 120. Skipping wins, so the cell is 160.dp[3][40]: skip gives 160. Take givesdp[2][10] + 120 = 180. Taking wins.dp[3][50]: skip gives 160. Take givesdp[2][20] + 120 = 220. Taking wins, which matches the memoized answer.
Notice dp[2][30] = 160. It comes from taking both of the first two items (weight 30, value 160). The greedy ratio choice settles on that same set and stops, while the table keeps checking whether swapping one of them for the heavier third item does better.
Cost
| Resource | Cost | Note |
|---|---|---|
| Time | O(nW) | One constant-time update per cell |
| Space | O(nW) | Full table, needed for reconstruction |
| Recursion depth | O(1) | No recursion at all |
For n = 1000 and W = 100000, the table has about 10^8 cells. A Python list of lists that size takes several gigabytes. Memory usually becomes the limit before time does, which is why the one-array chapter matters. The W factor also deserves suspicion. It depends on the numeric value of the capacity, not on how many digits it has. The chapter on pseudo-polynomial time explains why that distinction matters.
Common Errors
Other mistakes that come up often:
- Forgetting the skip copy. If you only assign
dp[i][c]when the item fits, cells withw > cstay at 0 instead of inheritingdp[i - 1][c]. - Building rows with
[[0] * (W + 1)] * (n + 1). This createsn + 1references to the same list, so writing one row overwrites them all. Use a list comprehension, as the code above does. - Reading
dp[i][c - w]instead ofdp[i - 1][c - w]. In the 2D table this silently lets an item be used more than once. That is the unbounded variant, not 0/1. - A table width of
Winstead ofW + 1. CapacityWitself must be a valid column.
Edge Cases
- Empty item list or capacity 0. The table is just row 0 or column 0, and the answer is 0. The code handles both without special cases.
- Items heavier than the capacity. The
w <= ctest is never true, so the row is a copy of the one above. - Zero-weight items. These are fine in the 2D table.
c - w = cstill reads from the row above, so each item is counted once. - Negative values. The take branch never wins for these, so they are effectively ignored. That is correct, since leaving them out is always at least as good.
- Non-integer weights. These cannot index columns. Scale them to integers, for example cents instead of dollars, or use a different technique.
Exact-Fill Variant
Sometimes the knapsack must be filled to exactly W. Only the base row changes: dp[0][0] = 0, and every other cell of row 0 is negative infinity, which marks it as unreachable.
NEG = float('-inf')
def knapsack_exact(values, weights, capacity):
n = len(values)
dp = [[NEG] * (capacity + 1) for _ in range(n + 1)]
dp[0][0] = 0
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[n][capacity]
print(knapsack_exact([60, 100, 120], [10, 20, 30], 50)) # 220
print(knapsack_exact([60, 100, 120], [10, 20, 30], 45)) # -infTesting Against Brute Force
On small inputs, compare the table result with an exhaustive search. Run this after defining knapsack_table:
import random
from itertools import combinations
def brute(values, weights, capacity):
best = 0
for r in range(len(values) + 1):
for combo in combinations(range(len(values)), r):
if sum(weights[i] for i in combo) <= capacity:
best = max(best, sum(values[i] for i in combo))
return best
for _ in range(500):
n = random.randint(0, 8)
vals = [random.randint(1, 50) for _ in range(n)]
wts = [random.randint(1, 15) for _ in range(n)]
cap = random.randint(0, 40)
assert knapsack_table(vals, wts, cap)[-1][cap] == brute(vals, wts, cap)
print("all tests passed")Exercise
For values [60, 100, 120], weights [10, 20, 30], compute dp[2][25] and dp[3][25] by hand.
Show answer
dp[2][25]: skip gives dp[1][25] = 60, take gives dp[1][5] + 100 = 100, so 100. dp[3][25]: item 3 weighs 30 > 25, so it copies the row above and the result is 100.
Exercise
A colleague changes dp[i - 1][c - w] to dp[i][c - w] in knapsack_table. What does the function now compute for the example with capacity 50, and why?
Show answer
It returns 300. Reading from the current row lets an item be added again after it was already taken in the same row, so items become reusable. That is the unbounded knapsack, and the best choice is five copies of (60, 10).
Exercise
Why can the inner loop over c run in either direction in the 2D version without changing the result?
Show answer
Every cell in row i reads only from row i - 1, which is complete before row i starts. No cell in row i depends on another cell in row i, so the order of columns within the row does not matter.