Sub topic 2
Trying Every Subset and Why It Does Not Scale
This chapter assumes you know basic Python (functions, loops, lists), can read a recursive function, and are comfortable with Big-O notation. It uses the running example from the previous chapter: values [60, 100, 120], weights [10, 20, 30], capacity 50.
The most direct way to solve the 0/1 knapsack problem is to try every possible choice of items, discard the choices that are too heavy, and keep the best of the rest. This approach is called exhaustive search, or brute force. It is always correct. It is also too slow for anything beyond a few dozen items. You will still use it often, because it makes a dependable reference for testing faster algorithms.
The Search Space: 2^n Subsets
In the 0/1 problem, each item is either in the knapsack or out of it. With n items there are two choices per item, so there are 2^n possible selections, counting the empty selection and the one that includes everything. A selection is feasible when its total weight is at most the capacity. The answer is the largest total value among the feasible selections.
For the running example there are 2^3 = 8 subsets:
| Subset (item indices) | Weight | Value | Feasible? |
|---|---|---|---|
| {} | 0 | 0 | yes |
| {0} | 10 | 60 | yes |
| {1} | 20 | 100 | yes |
| {2} | 30 | 120 | yes |
| {0, 1} | 30 | 160 | yes |
| {0, 2} | 40 | 180 | yes |
| {1, 2} | 50 | 220 | yes |
| {0, 1, 2} | 60 | 280 | no |
The best feasible subset is {1, 2}, worth 220. Brute force does nothing more clever than build this table and read off the maximum.
Enumerating Subsets with Bitmasks
A tidy way to list every subset is to count from 0 to 2^n - 1 and read each number as a bitmask. A bitmask is an integer whose binary digits act as on/off flags. Bit i set to 1 means item i is in the subset.
def knapsack_bitmask(values, weights, capacity):
n = len(values)
best_value, best_mask = 0, 0
for mask in range(1 << n): # 0 .. 2**n - 1
w = v = 0
for i in range(n):
if (mask >> i) & 1:
w += weights[i]
v += values[i]
if w <= capacity and v > best_value:
best_value, best_mask = v, mask
chosen = [i for i in range(n) if (best_mask >> i) & 1]
return best_value, chosen
print(knapsack_bitmask([60, 100, 120], [10, 20, 30], 50)) # (220, [1, 2])The outer loop runs 2^n times. The inner loop scans all n bits every time, so the total cost is O(n · 2^n) time and O(n) extra space. Recovering the chosen items costs nothing extra here, because you only need to remember the winning mask.
Enumerating Subsets with Recursion
The same search can be written as a decision tree. Look at item i and branch twice: skip it, or take it if it still fits. Then move on to item i + 1. Each path from the root to a leaf is one subset.
def knapsack_recursive(values, weights, capacity):
n = len(values)
def go(i, remaining):
if i == n:
return 0
best = go(i + 1, remaining) # skip item i
if weights[i] <= remaining: # take item i if it fits
best = max(best, values[i] + go(i + 1, remaining - weights[i]))
return best
return go(0, capacity)
print(knapsack_recursive([60, 100, 120], [10, 20, 30], 50)) # 220Each call does constant work besides its recursive calls, so the worst case is O(2^n) time. The recursion depth is n, so the extra space is O(n). The weights[i] <= remaining check is a simple form of pruning: it stops exploring a branch once that branch can only lead to infeasible subsets.
Why Pruning Does Not Save You
Pruning by weight helps when items are heavy compared with the capacity. In the worst case it removes nothing. If every item fits together, every branch is feasible and the tree has all 2^(n+1) − 1 nodes. You can check this by counting calls:
def count_calls(n):
calls = 0
def go(i, remaining):
nonlocal calls
calls += 1
if i == n:
return
go(i + 1, remaining)
if 1 <= remaining:
go(i + 1, remaining - 1)
go(0, n) # n items of weight 1, capacity n: nothing is pruned
return calls
for n in (5, 10, 15, 20):
print(n, count_calls(n))
# 5 63
# 10 2047
# 15 65535
# 20 2097151Every extra item doubles the work. The table below gives rough figures, assuming a plain Python loop checks about 10 million subsets per second. Compiled code might run 50 to 100 times faster, but that only buys about six or seven more items.
| n | Subsets (2^n) | Rough Python time |
|---|---|---|
| 20 | about 1.0 × 10^6 | under a second |
| 30 | about 1.1 × 10^9 | a few minutes |
| 40 | about 1.1 × 10^12 | a day or more |
| 60 | about 1.2 × 10^18 | thousands of years |
Exponential growth is the core problem. A faster machine shifts the limit by a constant number of items. It never changes the doubling.
Edge Cases
Brute force handles awkward inputs without any special code, which is part of why it works well as a reference:
- Empty item list. The only subset is the empty one, and the result is 0.
- Capacity 0. Only zero-weight items can be taken. Both versions handle this correctly.
- Zero-weight items. They always fit. With a positive value they are always taken.
- Items heavier than the capacity. They never appear in a feasible subset. The recursive version prunes them right away.
- Ties. Several subsets can share the best value. The bitmask version keeps the first one it finds because it uses a strict
>comparison. Tests should therefore compare values, not item lists.
Negative values or weights fall outside the standard problem definition. Brute force would still return a well-defined answer for them, but faster algorithms usually assume non-negative inputs, so the two may disagree.
Brute Force as a Test Oracle
A test oracle is a slow but trusted implementation used to check a faster one. Random small instances quickly expose off-by-one mistakes in capacity bounds or loop directions:
import random
def check(fast, trials=500):
for _ in range(trials):
n = random.randint(0, 10)
values = [random.randint(0, 50) for _ in range(n)]
weights = [random.randint(0, 20) for _ in range(n)]
capacity = random.randint(0, 60)
expected, _ = knapsack_bitmask(values, weights, capacity)
got = fast(values, weights, capacity)
assert got == expected, (values, weights, capacity, got, expected)
print("all trials passed")
check(knapsack_recursive)Keep n at 15 or below so each trial finishes quickly. Include zero weights and zero capacity in the random ranges, because those are where faster algorithms most often break. This listing calls knapsack_bitmask and knapsack_recursive, so define both before running it.
Summary
Brute force searches all 2^n subsets. The bitmask version costs O(n · 2^n) and the recursive version costs O(2^n). Both are correct and simple. In the worst case neither is practical beyond about 30 to 40 items. Pruning by weight cuts branches in good cases but cannot change the exponential worst case. The decision tree also shows the same subproblems being solved many times over, and that repetition is the opening for better methods.
Exercise
Modify knapsack_bitmask so it also returns how many of the 2^n subsets are feasible. For values [60, 100, 120], weights [10, 20, 30] and capacity 50, what count should it report?
Show answer
Add a counter that increments whenever w <= capacity, before the comparison with best_value, and return it along with the other results. Seven of the eight subsets are feasible. Only {0, 1, 2}, with weight 60, is too heavy, so the count is 7.
Exercise
You have 25 items, and every item weighs more than half the capacity. Roughly how many leaves does the pruned recursive search reach, and why?
Show answer
Any two of these items together exceed the capacity, so a feasible subset holds at most one item. The tree reaches one leaf for the empty set and one leaf for each single item, 26 leaves in total, instead of about 33 million. The search is fast in this case only because pruning removes almost every branch. The worst case is still 2^n.
Exercise
Why does the bitmask version cost O(n · 2^n) while the recursive version costs O(2^n), even though both examine the same subsets?
Show answer
The bitmask version rebuilds each subset's weight and value by scanning all n bits, which costs O(n) per subset. The recursive version carries the remaining capacity and the value total down the tree, so each node does O(1) work. A full binary tree of depth n has about 2^(n+1) nodes, which is O(2^n).