Skip to content
DSA Patterns
Menu
Language

Pattern #24

Knapsack & Subset DP

Advanced

Choose 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
1/8

0/1 knapsack, capacity 5, items (2,3) and (3,4).

0
0
0
1
0
2
0
3
0
4
0
5
StateW=5items=(2,3), (3,4)

dp[c] = best value at capacity c

Key:Active rangeMatchSettled

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

  1. 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).
  2. An odd sum cannot partition (LC 416). Target sum also rejects an odd sum + target and a target whose absolute value exceeds sum (LC 494).
  3. A count knapsack seeds dp[0] = 1 (LC 494, LC 518). A boolean partition does not.
  4. Profit past minProfit stays in that bucket, and the answer sums every member count there, modulo 10^9+7 (LC 879). The stone difference is sum - 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]!;
}
#StatusProblemTypeDone
  1. 1#416 Partition Equal Subset SumGuide
  2. 2#474 Ones and ZeroesGuide
  3. 3#494 Target SumGuide
  4. 4#518 Coin Change IIGuide
  5. 5#879 Profitable SchemesGuide
  6. 6#1049 Last Stone Weight IIGuide