Pattern #24
Knapsack & Subset DP
AdvancedChoose items under a capacity or hit an exact sum/target.
When to use
0/1 choices of items with weights/values, partition equal subset, target sum with +/-.
Recognition cues
- Partition equal subset sum
- Target sum / coin change II
- Boolean reachable dp[cap]
Common pitfalls
- 0/1 vs unbounded loop order (backward vs forward)
- Half-sum overflow when total is odd
- Using 2D when 1D reverse iteration is enough
90-second recognition drill
Which pattern fits best?
- Partition equal subset sum
- Target sum / coin change II
- Boolean reachable dp[cap]
Interactive
Mental model
A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.
Step 1 of 8
0
00
10
20
30
40
5StateW=5items=(2,3), (3,4)
dp[c] = best value at capacity c
How to think about it
dp[c] = best value (or reachable bool) with capacity c. For 0/1, iterate capacity downward so each item is used once. For unbounded, iterate upward. Subset-sum is knapsack with value=weight and bool OR.
Template shapes
| Shape | Core move | Example |
|---|---|---|
| Partition | The target is sum / 2. An odd sum cannot split. For each number, walk capacity downward: `dp[c] |
= dp[c - x]` |
| Zeros and ones | Two capacities. Each string is used once, so both capacities walk downward. dp[i][j] is the most strings that fit |
LC 474 |
| Target sum | need = (sum + target) / 2. An odd sum + target, or a target whose absolute value exceeds sum, returns 0. Count subsets of need downward, with dp[0] = 1 |
LC 494 |
| Coin combinations | The coin loop is outside the amount loop, so order does not matter and coins may repeat. dp[0] = 1. For each coin, dp[a] += dp[a - coin] from that coin up to amount |
LC 518 |
| Profitable schemes | dp[members][profit] counts schemes. Each crime walks both dimensions downward. Profit past minProfit lands in that bucket. The answer adds every member count there, modulo 10^9+7 |
LC 879 |
| Last stone | Boolean subset-sum up to sum / 2 finds the largest achievable s. The difference left is sum - 2 * s |
LC 1049 |
Complexity baseline
O(n·W) time and O(W) space for a one-capacity knapsack. LC 474 and LC 879 add a second capacity.
From template to problem
- A 0/1 item walks capacity downward, so the cell it reads has not yet used this item (LC 416, LC 474, LC 494, LC 879). An unbounded coin walks upward (LC 518).
- An odd sum cannot partition (LC 416). Target sum also rejects an odd
sum + targetand a target whose absolute value exceedssum(LC 494). - A count knapsack seeds
dp[0] = 1(LC 494, LC 518). A boolean partition does not. - Profit past
minProfitstays in that bucket, and the answer sums every member count there, modulo10^9+7(LC 879). The stone difference issum - 2 * s(LC 1049).
Template
Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.
Knapsack & Subset DP · Template
/** Knapsack template: partition equal subset sum (0/1 bool DP). */
export function canPartition(nums: number[]): boolean {
const sum = nums.reduce((a, b) => a + b, 0);
if (sum % 2) return false;
const target = sum / 2;
const dp = new Array<boolean>(target + 1).fill(false);
dp[0] = true;
for (const x of nums) {
for (let c = target; c >= x; c--) dp[c] = dp[c]! || dp[c - x]!;
}
return dp[target]!;
}
/** Knapsack template: partition equal subset sum (0/1 bool DP). */
export function canPartition(nums: number[]): boolean {
const sum = nums.reduce((a, b) => a + b, 0);
if (sum % 2) return false;
const target = sum / 2;
const dp = new Array<boolean>(target + 1).fill(false);
dp[0] = true;
for (const x of nums) {
for (let c = target; c >= x; c--) dp[c] = dp[c]! || dp[c - x]!;
}
return dp[target]!;
}
#StatusProblemTypeDifficultyDone
- 1#416 Partition Equal Subset SumGuidemedium
- 2#474 Ones and ZeroesGuidemedium
- 3#494 Target SumGuidemedium
- 4#518 Coin Change IIGuidemedium
- 5#879 Profitable SchemesGuidehard
- 6#1049 Last Stone Weight IIGuidemedium