Sub topic 2
Top-Down Solution with Memoization
This chapter assumes you know Python functions and loops, recursion, Big-O notation, and nested lists. It also assumes the take-or-skip recurrence from the previous chapter: best(i, c) is the best value you can get from items i onward with remaining capacity c.
Top-Down Solution with Memoization
If you call the recurrence directly, it reaches the same (i, c) state many times, so plain recursion takes exponential time. Memoization stores each result the first time it is computed. With n items and capacity W, there are at most (n + 1)(W + 1) states, and each one takes O(1) work. That gives O(nW) time.
from functools import lru_cache
def knapsack_memo(values, weights, capacity):
n = len(values)
@lru_cache(maxsize=None)
def best(i, c):
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
return max(skip, values[i] + best(i + 1, c - weights[i]))
return skip
return best(0, capacity)
print(knapsack_memo([60, 100, 120], [10, 20, 30], 50)) # 220Bottom-Up Solution with a DP Table
In the table version, dp[i][c] is the best value using the first i items with capacity c. Row i depends only on row i - 1, so you can fill the rows in order without recursion.
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])Recovering Which Items Were Chosen
The second loop in knapsack_table starts at dp[n][W] and walks back one row at a time. If dp[i][c] differs from dp[i - 1][c], item i - 1 must have been taken. In that case the loop subtracts that item's weight from c. Otherwise the item was skipped and c stays the same. A common bug is to forget to reduce c after a take.
Using One Array: Why the Loop Runs Backwards
Each row reads only from the row above it. That means one array of size W + 1 is enough, which cuts the space to O(W). The catch is the loop order. When the capacity loop runs from high to low, dp[c - w] still holds the previous row's value, so each item is used at most once.
def knapsack_01_1d(values, weights, capacity):
dp = [0] * (capacity + 1)
for v, w in zip(values, weights):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_01_1d([60, 100, 120], [10, 20, 30], 50)) # 220The one-array version gives up the full table. Without the table, you cannot reconstruct the chosen items the way knapsack_table does.
Exercise
In knapsack011d, change the inner loop to run forwards, using range(w, capacity + 1). What does it return on the example input, and why?
Show answer
It returns 300. When c rises, dp[c - w] may already include the current item, so the same item can be added again. Here, item (100, 20) is taken twice and item (60, 10) once: 200 + 60 = 260 is not optimal, but five copies of (60, 10) give 300. This forward loop is exactly the unbounded knapsack.
Exercise
What are the time and space costs of knapsacktable and knapsack01_1d?
Show answer
Both take O(nW) time. knapsacktable uses O(nW) space, and knapsack01_1d uses O(W) space.