Learn the pattern · ~14 min
0/1 Knapsack
also called subset sum, capacity DP
Every item is a take-or-skip choice. Whether the first k items can make a total rem depends only on k and rem, not on how you got there, so solve each (k, rem) once: a table of totals, then one row walked from the target downward so each item is used at most once.
Reach for it when you read
- +Pick a subset whose sum or weight is exactly (or at most) X, each item at most once.
- +"Split into two groups with equal sums" (the target is half the total) or "with the smallest difference" (fill up to half the total and take the largest reachable sum).
- +"Put a
+or−in front of each number to reach S": the plus group must sum to (total + S) / 2. - +"Best value within a budget / weight limit, each item once": the classic knapsack, with
maxin the cell. - +"How many subsets / ways reach exactly X": the same table with counts.
- +Your brute-force recursion only needs two arguments: which item is next and how much is left.
Not this one when
- ×Each item can be used again and again (unlimited coins): unbounded knapsack, the capacity loop goes forward.
- ×You may take a fraction of an item: fractional knapsack, greedy by value per kg.
- ×The capacity is huge (10⁹) but there are only about 40 items: no array can be indexed by it; split the items in half (meet in the middle).
- ×Split into k > 2 equal groups: one capacity can't track k groups; use a bitmask over the used items.
Learn 0/1 Knapsack
First, what does "0/1 knapsack" mean?
A knapsack is a bag with a limit: say 5 kg, with items of 2, 3 and 4 kg. 2 + 3 fills it exactly.
The 0/1 means every item is taken 0 times or 1 time: you can't take the 2 twice. The limit can be a weight, a budget or an exact sum.
The problem: split the bill
Four items cost [2, 3, 5, 6] (in ₹100s). Can two friends split them so each pays the same?
The total is 16, so each pays 8: does some group of items add up to exactly 8? Try it by hand:
| group | sum | how you found it |
|---|---|---|
| 2, 3 | 5 | cheapest first: next is 5, but 5 + 5 = 10 overshoots |
| 3, 5 | 8 | drop the 2, keep 3 and 5 |
| 2, 6 | 8 | the other friend's share |
Yes: {3, 5} and {2, 6}. Cheapest-first got stuck, and n items have 2ⁿ groups to try.
One choice per item
Walk the items in order. At each one, two moves:
Take the item (if it still fits), or skip it.
Write can(i, rem) for "can the items from i onward make exactly rem?" The start is can(0, 8).
| at | what happens | next question |
|---|---|---|
| item 2, need 8 | take it: 8 − 2 = 6 left | can(1, 6) |
| or skip it: still need 8 | can(1, 8) |
|
| need 0 | the group is complete | yes |
| no items left, need > 0 | nothing can fill the gap | no |
The answer is yes if either move leads to a yes.
The brute force: the plain recursion
// can the items a[i..] make exactly rem?
bool can(int i, int rem, const vector<int>& a) {
if (rem == 0) return true; // nothing left to make: done
if (i == (int)a.size()) return false; // out of items, rem still > 0
bool take = a[i] <= rem && can(i + 1, rem - a[i], a);
bool skip = can(i + 1, rem, a);
return take || skip;
}It returns true. Its calls, three levels deep:
- can(0, 8)
- take 2: can(1, 6)
- take 3: can(2, 3)
- skip 5: can(3, 3)← here
- skip 3: can(2, 6)
- take 5: can(3, 1)
- skip 5: can(3, 6)
- skip 2: can(1, 8)
- take 3: can(2, 5)
- take 5: can(3, 0) yes
- skip 5: can(3, 5)
- skip 3: can(2, 8)
- take 5: can(3, 3)← and here
- skip 5: can(3, 8)
Every item doubles the tree: 2ⁿ paths. 30 items already take 1.5 seconds, and the problem allows 200 (1.6 × 10⁶⁰ paths). Time limit exceeded.
The one thought: the same question comes back
Look at the two arrows. Take 2 and 3, skip 5: you're at item 3 (the 6) needing 3. Skip 2 and 3, take 5: the same place, item 3 needing 3.
Does the path matter? No: only which items are ahead (i) and how much is missing (rem). The answer is "no" both times (6 doesn't make 3).
So a question is fixed by the pair (i, rem): at most (n + 1) × (target + 1) pairs, about 2 × 10⁶ for n = 200 and target 10⁴. Answer each once:
// memo[i][rem]: -1 not asked yet, 0 no, 1 yes
bool can(int i, int rem, const vector<int>& a, vector<vector<int>>& memo) {
if (rem == 0) return true;
if (i == (int)a.size()) return false;
int& m = memo[i][rem];
if (m != -1) return m; // this (i, rem) was answered before
bool take = a[i] <= rem && can(i + 1, rem - a[i], a, memo);
bool skip = can(i + 1, rem, a, memo);
return m = take || skip;
}Bottom-up: one row per item
Fill it from the small end: dp[i][w] = "can the first i items make exactly w?" Row 0 (no items) makes only 0. Row i copies row i − 1 (skip) and adds w wherever w − item was in it (take).
bool subsetSum(const vector<int>& a, int target) {
int n = a.size();
vector<vector<bool>> dp(n + 1, vector<bool>(target + 1, false));
dp[0][0] = true; // no items make 0, and nothing else
for (int i = 1; i <= n; i++)
for (int w = 0; w <= target; w++) {
bool skip = dp[i - 1][w];
bool take = w >= a[i - 1] && dp[i - 1][w - a[i - 1]];
dp[i][w] = skip || take;
}
return dp[n][target];
}The totals each row can make, up to 8:
| after item | what happens | totals it can make |
|---|---|---|
| none | the empty group | 0 |
| 2 | keep 0; 0 + 2 = 2 | 0, 2 |
| 3 | keep 0, 2; add 3 to each: 3, 5 | 0, 2, 3, 5 |
| 5 | keep 0, 2, 3, 5; add 5: 5, 7, 8 (10 is over) | 0, 2, 3, 5, 7, 8 |
| 6 | keep those; add 6: 6, 8 (the rest are over) | 0, 2, 3, 5, 6, 7, 8 |
8 shows up in the last row: true, the same answer as the brute force.
Down to one row, walked backward
Row i reads only row i − 1, so keep one row and update it in place. The catch: when you write dp[w], the cell dp[w − x] you read must still hold the old row's value. Walk w from the target down, and it does: every cell below w is still untouched.
bool canPartition(const vector<int>& nums) {
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % 2 == 1) return false; // an odd total can't split evenly
int target = total / 2;
vector<bool> dp(target + 1, false);
dp[0] = true; // the empty group makes 0
for (int x : nums)
for (int w = target; w >= x; w--) // backward: each item at most once
if (dp[w - x]) dp[w] = true;
return dp[target];
}Item 5 arriving, the row holding 0, 2, 3, 5:
| w | reads dp[w − 5] | what happens |
|---|---|---|
| 8 | dp[3] = true | 3 + 5: 8 becomes true |
| 7 | dp[2] = true | 2 + 5: 7 becomes true |
| 6 | dp[1] = false | stays false |
| 5 | dp[0] = true | already true |
Why not walk upward, for (w = x; w <= target; w++)? Then a cell you just set is read again in the same pass: the item gets reused. On [1, 2, 5] (total 8, target 4), the upward loop marks 1, 2, 3, 4 using the 1 again and again, and says true. But no group makes 4: {1, 2} is 3, and 5 is too big. Backward correctly says false.
Why it's O(n × target)
Every item visits each total once, with O(1) work: O(n × target) time, 200 × 10⁴ = 2 × 10⁶ steps. One row of target + 1 cells: O(target) space.
From 2ⁿ groups down to n × target cells, because only "which item, how much left" matters.
Best value under a weight limit? Put values in the cells
The classic knapsack: items weigh [2, 3, 5, 6] and are worth [3, 5, 8, 9]; the bag holds 8. Cells now hold the best value, not true/false:
vector<int> dp(W + 1, 0); // dp[c] = best value with capacity c
for (int i = 0; i < n; i++)
for (int c = W; c >= wt[i]; c--)
dp[c] = max(dp[c], dp[c - wt[i]] + val[i]);The answer is 13: the 3 kg and 5 kg items (5 + 8).
Count the groups? Add instead of OR
Target Sum puts + or − before each number to reach S. The plus group P and minus group M satisfy P − M = S and P + M = total, so P = (total + S) / 2. For [1, 1, 2, 3] and S = 1, count groups summing to 4:
vector<int> ways(t + 1, 0);
ways[0] = 1; // one way to make 0: take nothing
for (int x : nums)
for (int w = t; w >= x; w--) ways[w] += ways[w - x];3 groups: {1, 3} with either 1, and {1, 1, 2}. If total + S is odd, or |S| > total, the answer is 0.
Remember this
- Items with a size, a budget, each item once: 0/1 knapsack. Write the state in words first: "can the first i items make w?"
- Items in the outer loop, the budget walked backward. Forward lets an item be reused, which is unbounded knapsack.
- Seed
dp[0] = true(or 1 way, or value 0). An odd total can't split in two. - Whenever a problem asks you to pick a subset that hits, or stays under, a number, it's this table.
Practise it on Partition Equal Subset Sum, then Target Sum (count the groups), Last Stone Weight II (the largest reachable sum up to half the total), Ones and Zeroes (two budgets, both loops backward) and Profitable Schemes (a budget and an "at least" target).
Below, watch Partition Equal Subset Sum run line by line.
Watch it work, line by line
Partition Equal Subset Sum ↗, nums = [2, 3, 5, 6] → true ({3, 5} and {2, 6}, 8 each). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
Break it
Each card changes one line of the template the way it usually goes wrong in an interview. Before you open it, guess what the broken version prints.
Capacity loop forward: for (int w = x; w <= target; w++)
on [1, 2, 5]
What goes wrong?
for (int w = x; w <= target; w++)broken → true
correct → false
Going up, dp[w − x] was already updated for this item. The single 1 reaches 1, then 2, 3 and 4 from itself: 1 + 1 + 1 + 1 = 4.
Drop if (total % 2 == 1) return false;
on [1, 2, 4]
What goes wrong?
if (total % 2 == 1) return false;broken → true
correct → false
The total is 7, and 7 / 2 rounds down to 3. {1, 2} makes 3, but the other group makes 4: not equal.
Drop dp[0] = true;
on [2, 3, 5, 6]
What goes wrong?
dp[0] = true;broken → false
correct → true
Every true cell is built on the empty group making 0. Without that seed, no take step ever fires.
Swap the loops: totals outside (w from target down to 0), items inside, with w >= x checked in the if
on [2, 3, 5, 6]
What goes wrong?
w from target down to 0), items inside, with w >= x checked in the ifbroken → false
correct → true
When dp[8] is decided, the smaller totals haven't been filled yet, so only a single item worth exactly 8 could reach it. Items must be the outer loop.
Counting recursion: if (rem == 0) return 1; checked before if (k == 0) return rem == 0;
on [0, 0, 1, 2], X = 3
What goes wrong?
if (rem == 0) return 1; checked before if (k == 0) return rem == 0;broken → 1
correct → 4
Once {1, 2} makes 3 the early stop returns, so the two 0s are never offered. Each 0 can be in or out: 4 subsets. Stop only when the items run out.
When to use it, and when not
Ask yourself
Does each item get one take-or-skip decision (never reused, never split), with a sum or capacity that is small enough to index an array?
Reach for it when
- +choose a subset with sum/weight constraint
- +partition into two equal/closest sums
- +target with +/- signs (reduces to subset sum)
- +n*W up to ~1e7-1e8
- +W small; values can be large
It fails when
- ×Items can be reused unlimited timesuse Unbounded knapsack (capacity loop forward)
- ×W is huge (e.g. 1e9) but n <= ~40use Meet in the middle
- ×n <= 20 with complex constraints between itemsuse Bitmask DP
- ×Items are fractionaluse Greedy by value/weight
- ×Order of picking matters / it's sequence alignmentuse A different DP over sequences
Looks like it, isn't (and the other way round)
- Last Stone Weight II looks like Top-K Elements, needs this pattern
Its sibling last-stone-weight is a heap simulation, but greedy smashing is not optimal here. Every outcome is |S1 - S2| for some split, so find the subset sum closest to total/2.
- Tallest Billboard looks like Backtracking, needs this pattern
3n assignments collapse into dp[difference] = best shorter-side height (the editorial also shows meet-in-the-middle).
- Partition to K Equal Sum Subsets looks like 0/1 Knapsack, needs Bitmask DP
k buckets cannot be tracked by a single capacity; use bitmask DP or pruned backtracking.
- Count of Sub-Multisets With Bounded Sum looks like 0/1 Knapsack, needs Bounded (Multiple) Knapsack
Expanding every copy is O(n*S). Grouping equal values and using residue-class window sums makes it O(sqrt(S) * S).
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why does the capacity loop go backward in 0/1 knapsack?Reveal
So
dp[w - x]still comes from before item x was considered. Going forward would let x be used twice.2What is
dp[0]and why does it matter?RevealTrue (or 0, or 1 for counts): the empty subset reaches sum 0. Every other cell is built from it.
3Partition into two equal halves: what do you check first?Reveal
That the total is even. Then search for a subset summing to total / 2.
4In the 2D table, where does "each item at most once" come from?Reveal
The take branch reads row i − 1, which has no item i in it. In one row, reading right to left keeps dp[w − x] at its row i − 1 value.
5When counting subsets, why is
if (rem == 0) return 1;wrong as the first check?RevealIf the items include 0s, a subset that already makes the target can still add a 0. Stopping early misses those; stop only when the items run out (
k == 0).
Practice ladder
- 1Partition Equal Subset Sumthe hookMedium
- 2Money Sumsevery reachable sumMedium
- 3Book Shopbest valueMedium
- 4Target Sumcount the subsetsMedium
- 5Last Stone Weight IIclosest to halfMedium
- 6Ones and Zeroestwo capacitiesMedium
- 7Two Sets IIcount the subsetsMedium
- 8Profitable Schemesat least a targetHard
- 9Tallest Billboardstate is a differenceHard
Finished 0/1 Knapsack? Mark it done and Lessgo moves you to the next step.