cswork / templatesOpen the Line 500 list

STOP 24 · DYNAMIC PROGRAMMING

Knapsack and Combination Counting

0/1 knapsack backwards, unbounded forwards O(n × target)

Contest ratings Rating 2092–Rating 2204· median Rating 2148(2 of 10 problems rated by zerotrac)

Open the Line 500 list · stop 24 · 10 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 5 companies · in 5 reportsAirbnb 1, Amazon 1, Pinterest 1, Squarepoint 1, WorldQuant 1

Warm up with this one

LC 322Coin ChangeMedium
Stuck? Peek at the approach

Use unbounded knapsack to minimize the number of choices, handling unreachable states and amount zero.

Key points

  1. The 0/1 knapsack loops capacity downwards so dp[s-x] is still the value without x; the unbounded version loops upwards so an item can be reused.
  2. Items outside and capacity inside counts combinations (order ignored); capacity outside and items inside counts permutations.
  3. Many problems reduce to a knapsack: equal-sum partition asks whether sum/2 is reachable, and target sum asks for (sum+target)/2.

Common pitfalls

  • Looping a 0/1 knapsack forwards uses the same item many times.
  • For counting, dp[0] = 1 (choosing nothing is one way); for min/max, dp[0] = 0 and everything else starts at infinity.
  • Reducing to (sum+target)/2 without checking parity and sign gives a bad index.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Dynamic programming · coin change

Coins 1, 3, 4, unlimited of each: make 6

Try your own input
0dp[0]
∞dp[1]
∞dp[2]
∞dp[3]
∞dp[4]
∞dp[5]
∞dp[6]
CurrentDiscovered / computedAnswer
Amount
6
Current
—
Fewest coins
not reachable yet

dp[0] = 0 and every other state starts at ∞ (unreachable). dp[x] is the fewest coins that make x.

InvariantAmounts go up one by one; when dp[x] is updated, every smaller amount is already optimal.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 322, with it.

Python
def count_subsets(nums: list[int], target: int) -> int:
    """Ways to pick a subset (each item at most once) that sums to target."""
    dp = [1] + [0] * target  # dp[s]: ways to reach sum s
    for x in nums:
        for s in range(target, x - 1, -1):  # backwards: x is used at most once
            dp[s] += dp[s - x]
    return dp[target]


def count_combinations(coins: list[int], amount: int) -> int:
    """Ways to make amount with unlimited coins, order ignored."""
    dp = [1] + [0] * amount
    for coin in coins:  # coins outside: each multiset is counted once
        for s in range(coin, amount + 1):  # forwards: a coin may be reused
            dp[s] += dp[s - coin]
    return dp[amount]
C++
// Ways to pick a subset (each item at most once) that sums to target.
long long countSubsets(const vector<int>& nums, int target) {
    vector<long long> dp(target + 1, 0);  // dp[s]: ways to reach sum s
    dp[0] = 1;
    for (int x : nums)
        for (int s = target; s >= x; s--) dp[s] += dp[s - x];  // backwards: x used at most once
    return dp[target];
}

// Ways to make amount with unlimited coins, order ignored.
long long countCombinations(const vector<int>& coins, int amount) {
    vector<long long> dp(amount + 1, 0);
    dp[0] = 1;
    for (int coin : coins)  // coins outside: each multiset is counted once
        for (int s = coin; s <= amount; s++) dp[s] += dp[s - coin];  // forwards: reuse allowed
    return dp[amount];
}
Java
class Solution {
    // Ways to pick a subset (each item at most once) that sums to target.
    long countSubsets(int[] nums, int target) {
        long[] dp = new long[target + 1]; // dp[s]: ways to reach sum s
        dp[0] = 1;
        for (int x : nums)
            for (int s = target; s >= x; s--) dp[s] += dp[s - x]; // backwards: x used at most once
        return dp[target];
    }

    // Ways to make amount with unlimited coins, order ignored.
    long countCombinations(int[] coins, int amount) {
        long[] dp = new long[amount + 1];
        dp[0] = 1;
        for (int coin : coins) // coins outside: each multiset is counted once
            for (int s = coin; s <= amount; s++) dp[s] += dp[s - coin]; // forwards: reuse allowed
        return dp[amount];
    }
}
Go
// countSubsets returns the ways to pick a subset (each item at most once) that sums to target.
func countSubsets(nums []int, target int) int {
	dp := make([]int, target+1) // dp[s]: ways to reach sum s
	dp[0] = 1
	for _, x := range nums {
		for s := target; s >= x; s-- { // backwards: x is used at most once
			dp[s] += dp[s-x]
		}
	}
	return dp[target]
}

// countCombinations returns the ways to make amount with unlimited coins, order ignored.
func countCombinations(coins []int, amount int) int {
	dp := make([]int, amount+1)
	dp[0] = 1
	for _, coin := range coins { // coins outside: each multiset is counted once
		for s := coin; s <= amount; s++ { // forwards: a coin may be reused
			dp[s] += dp[s-coin]
		}
	}
	return dp[amount]
}

Common variants

Problems at this stop also need the 6 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Variant matrix: each cell shows the line or two that decide it
Best valueCombinationsOrderingsReachable?Fewest items
0/1 (each item once)0/1 knapsack for the best valuefor c in range(cap, w - 1, -1): dp[c] = max(dp[c], dp[c - w] + v)for (int c = cap; c >= weights[i]; c--) dp[c] = max(dp[c], dp[c - weights[i]] + values[i]);for (int c = cap; c >= weights[i]; c--) dp[c] = Math.max(dp[c], dp[c - weights[i]] + values[i]);for c := capacity; c >= w; c-- { dp[c] = max(dp[c], dp[c-w]+values[i])Main templatefor s in range(target, x - 1, -1): dp[s] += dp[s - x]for (int s = target; s >= x; s--) dp[s] += dp[s - x];for (int s = target; s >= x; s--) dp[s] += dp[s - x];for s := target; s >= x; s-- { dp[s] += dp[s-x]

Each item once and order matters is not a knapsack loop any more: count the subsets that reach the target, then multiply by the orderings of each subset size. Interviews rarely ask it.

0/1 knapsack: can the sum be reachedfor s in range(target, x - 1, -1): dp[s] = dp[s] or dp[s - x]for (int s = target; s >= x; s--) dp[s] = dp[s] || dp[s - x];for (int s = target; s >= x; s--) dp[s] = dp[s] || dp[s - x];for s := target; s >= x; s-- { dp[s] = dp[s] || dp[s-x]

Keep the backwards loop of the reachability cell and store counts instead: dp[0] = 0, everything else infinity, and dp[s] = min(dp[s], dp[s - x] + 1).

Unbounded (unlimited)

The same line as 0/1 best value with the capacity loop run forwards, so an item can be chosen again.

Main templatefor s in range(coin, amount + 1): dp[s] += dp[s - coin]for (int s = coin; s <= amount; s++) dp[s] += dp[s - coin];for (int s = coin; s <= amount; s++) dp[s] += dp[s - coin];for s := coin; s <= amount; s++ { dp[s] += dp[s-coin]Unbounded knapsack counting orderingsfor s in range(1, target + 1): for x in nums:for (int s = 1; s <= target; s++) for (int x : nums)for (int s = 1; s <= target; s++) for (int x : nums)for s := 1; s <= target; s++ { for _, x := range nums {

Check whether the combination count is above 0, or swap += for or when only true or false is needed. LC 139 (Word Break) is the ordered version: positions outside, words inside.

Unbounded knapsack for the fewest itemsfor s in range(coin, amount + 1): dp[s] = min(dp[s], dp[s - coin] + 1)for (int s = coin; s <= amount; s++) dp[s] = min(dp[s], dp[s - coin] + 1);for (int s = coin; s <= amount; s++) dp[s] = Math.min(dp[s], dp[s - coin] + 1);for s := coin; s <= amount; s++ { dp[s] = min(dp[s], dp[s-coin]+1)
Bounded (binary splitting)Bounded knapsack by binary splittingtake = min(k, cnt) dp[c] = max(dp[c], dp[c - take * w] + take * v)int take = min(k, cnt); dp[c] = max(dp[c], dp[c - take * w] + take * v);int take = Math.min(k, cnt); dp[c] = Math.max(dp[c], dp[c - take * w] + take * v);take := min(k, cnt) dp[c] = max(dp[c], dp[c-take*w]+take*v)

Counting cannot use binary splitting: two bundles can be the same size (5 = 1 + 2 + 2), so one quantity is counted twice. Enumerate 0 to cnt copies of each item instead, or remove that loop with prefix sums.

With limited copies and order mattering, a one-dimensional knapsack state cannot remember how many copies are used; it becomes multiset permutation counting, which interviews rarely ask.

Reachability does not mind double counting: split into bundles, then use the backwards or of the 0/1 reachability cell.

After splitting, a bundle counts as take items: dp[c] = min(dp[c], dp[c - take * w] + take).

0/1 knapsack for the best valueO(n × cap) time · O(cap) space

Each item at most once, a capacity limit, the largest total value: run the capacity backwards and take the max. LC 1049 (Last Stone Weight II) is this with each stone as both weight and value, capped at half the total.

Python
def knapsack_01(weights: list[int], values: list[int], cap: int) -> int:
    """Best total value within capacity cap, each item at most once."""
    dp = [0] * (cap + 1)  # dp[c]: best value with capacity c
    for w, v in zip(weights, values):
        for c in range(cap, w - 1, -1):  # backwards: the item is used at most once
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[cap]
C++
// Best total value within capacity cap, each item at most once.
int knapsack01(const vector<int>& weights, const vector<int>& values, int cap) {
    vector<int> dp(cap + 1, 0);  // dp[c]: best value with capacity c
    for (size_t i = 0; i < weights.size(); i++)
        for (int c = cap; c >= weights[i]; c--)  // backwards: item i is used at most once
            dp[c] = max(dp[c], dp[c - weights[i]] + values[i]);
    return dp[cap];
}
Java
class Solution {
    // Best total value within capacity cap, each item at most once.
    int knapsack01(int[] weights, int[] values, int cap) {
        int[] dp = new int[cap + 1]; // dp[c]: best value with capacity c
        for (int i = 0; i < weights.length; i++)
            for (int c = cap; c >= weights[i]; c--) // backwards: item i is used at most once
                dp[c] = Math.max(dp[c], dp[c - weights[i]] + values[i]);
        return dp[cap];
    }
}
Go
// knapsack01 returns the best total value within capacity cap, each item at most once.
func knapsack01(weights, values []int, capacity int) int {
	dp := make([]int, capacity+1) // dp[c]: best value with capacity c
	for i, w := range weights {
		for c := capacity; c >= w; c-- { // backwards: item i is used at most once
			dp[c] = max(dp[c], dp[c-w]+values[i])
		}
	}
	return dp[capacity]
}
0/1 knapsack: can the sum be reachedO(n × target) time · O(target) space

When the question is only whether a sum is reachable: boolean states combined with or. LC 416 (Partition Equal Subset Sum) checks the parity of the total, then asks whether half of it is reachable.

Python
def can_partition(nums: list[int]) -> bool:
    """Can nums be split into two groups with equal sums?"""
    total = sum(nums)
    if total % 2:
        return False
    target = total // 2
    dp = [True] + [False] * target  # dp[s]: some subset sums to s
    for x in nums:
        for s in range(target, x - 1, -1):  # backwards: x is used at most once
            dp[s] = dp[s] or dp[s - x]
    return dp[target]
C++
// Can nums be split into two groups with equal sums?
bool canPartition(const vector<int>& nums) {
    int total = accumulate(nums.begin(), nums.end(), 0);
    if (total % 2) return false;
    int target = total / 2;
    vector<char> dp(target + 1, false);  // dp[s]: some subset sums to s
    dp[0] = true;
    for (int x : nums)
        for (int s = target; s >= x; s--)  // backwards: x is used at most once
            dp[s] = dp[s] || dp[s - x];
    return dp[target];
}
Java
class Solution {
    // Can nums be split into two groups with equal sums?
    boolean canPartition(int[] nums) {
        int total = Arrays.stream(nums).sum();
        if (total % 2 != 0) return false;
        int target = total / 2;
        boolean[] dp = new boolean[target + 1]; // dp[s]: some subset sums to s
        dp[0] = true;
        for (int x : nums)
            for (int s = target; s >= x; s--) // backwards: x is used at most once
                dp[s] = dp[s] || dp[s - x];
        return dp[target];
    }
}
Go
// canPartition reports whether nums can be split into two groups with equal sums.
func canPartition(nums []int) bool {
	total := 0
	for _, x := range nums {
		total += x
	}
	if total%2 != 0 {
		return false
	}
	target := total / 2
	dp := make([]bool, target+1) // dp[s]: some subset sums to s
	dp[0] = true
	for _, x := range nums {
		for s := target; s >= x; s-- { // backwards: x is used at most once
			dp[s] = dp[s] || dp[s-x]
		}
	}
	return dp[target]
}
Unbounded knapsack for the fewest itemsO(n × amount) time · O(amount) space

Unlimited copies and the fewest items to hit the sum exactly: capacity forwards, start every state at infinity except dp[0], and take min(dp[s], dp[s - coin] + 1). LC 322 (Coin Change) and LC 279 (Perfect Squares) have this shape.

Python
def min_coins(coins: list[int], amount: int) -> int:
    """Fewest coins (each reusable) that sum to amount, or -1."""
    INF = amount + 1  # more coins than any answer can need
    dp = [0] + [INF] * amount  # dp[s]: fewest coins for sum s
    for coin in coins:
        for s in range(coin, amount + 1):  # forwards: the coin may be reused
            dp[s] = min(dp[s], dp[s - coin] + 1)
    return dp[amount] if dp[amount] < INF else -1
C++
// Fewest coins (each reusable) that sum to amount, or -1.
int minCoins(const vector<int>& coins, int amount) {
    const int INF = amount + 1;  // more coins than any answer can need
    vector<int> dp(amount + 1, INF);  // dp[s]: fewest coins for sum s
    dp[0] = 0;
    for (int coin : coins)
        for (int s = coin; s <= amount; s++)  // forwards: the coin may be reused
            dp[s] = min(dp[s], dp[s - coin] + 1);
    return dp[amount] < INF ? dp[amount] : -1;
}
Java
class Solution {
    // Fewest coins (each reusable) that sum to amount, or -1.
    int minCoins(int[] coins, int amount) {
        final int INF = amount + 1; // more coins than any answer can need
        int[] dp = new int[amount + 1]; // dp[s]: fewest coins for sum s
        Arrays.fill(dp, INF);
        dp[0] = 0;
        for (int coin : coins)
            for (int s = coin; s <= amount; s++) // forwards: the coin may be reused
                dp[s] = Math.min(dp[s], dp[s - coin] + 1);
        return dp[amount] < INF ? dp[amount] : -1;
    }
}
Go
// minCoins returns the fewest coins (each reusable) that sum to amount, or -1.
func minCoins(coins []int, amount int) int {
	inf := amount + 1 // more coins than any answer can need
	dp := make([]int, amount+1) // dp[s]: fewest coins for sum s
	for s := 1; s <= amount; s++ {
		dp[s] = inf
	}
	for _, coin := range coins {
		for s := coin; s <= amount; s++ { // forwards: the coin may be reused
			dp[s] = min(dp[s], dp[s-coin]+1)
		}
	}
	if dp[amount] < inf {
		return dp[amount]
	}
	return -1
}
Unbounded knapsack counting orderingsO(n × target) time · O(target) space

When different orders count as different ways (1+2 and 2+1 are two): sums in the outer loop, items in the inner loop, so every sum tries each possible last pick. LC 377 (Combination Sum IV) says combinations but counts orderings.

Python
def count_sequences(nums: list[int], target: int) -> int:
    """Ordered ways to reach target with unlimited reuse: (1, 2) and (2, 1) differ."""
    dp = [1] + [0] * target  # dp[s]: sequences that sum to s
    for s in range(1, target + 1):  # sums outside: each sum tries every last pick
        for x in nums:
            if x <= s:
                dp[s] += dp[s - x]
    return dp[target]
C++
// Ordered ways to reach target with unlimited reuse: (1, 2) and (2, 1) differ.
long long countSequences(const vector<int>& nums, int target) {
    vector<long long> dp(target + 1, 0);  // dp[s]: sequences that sum to s
    dp[0] = 1;
    for (int s = 1; s <= target; s++)  // sums outside: each sum tries every last pick
        for (int x : nums)
            if (x <= s) dp[s] += dp[s - x];
    return dp[target];
}
Java
class Solution {
    // Ordered ways to reach target with unlimited reuse: (1, 2) and (2, 1) differ.
    long countSequences(int[] nums, int target) {
        long[] dp = new long[target + 1]; // dp[s]: sequences that sum to s
        dp[0] = 1;
        for (int s = 1; s <= target; s++) // sums outside: each sum tries every last pick
            for (int x : nums)
                if (x <= s) dp[s] += dp[s - x];
        return dp[target];
    }
}
Go
// countSequences returns the ordered ways to reach target with unlimited reuse.
func countSequences(nums []int, target int) int {
	dp := make([]int, target+1) // dp[s]: sequences that sum to s
	dp[0] = 1
	for s := 1; s <= target; s++ { // sums outside: each sum tries every last pick
		for _, x := range nums {
			if x <= s {
				dp[s] += dp[s-x]
			}
		}
	}
	return dp[target]
}
0/1 knapsack with two capacitiesO(len × m × n) time · O(m × n) space

When each item spends two resources at once (zeros and ones, say): add a dimension and run both capacities backwards. LC 474 (Ones and Zeroes) maximises the count; LC 879 (Profitable Schemes) counts with the same two dimensions.

Python
def max_strings(strs: list[str], m: int, n: int) -> int:
    """Most strings you can pick with at most m zeros and n ones in total."""
    dp = [[0] * (n + 1) for _ in range(m + 1)]  # dp[i][j]: best with i zeros, j ones
    for s in strs:
        zeros, ones = s.count("0"), s.count("1")
        for i in range(m, zeros - 1, -1):  # both capacities backwards: s is used once
            for j in range(n, ones - 1, -1):
                dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
    return dp[m][n]
C++
// Most strings you can pick with at most m zeros and n ones in total.
int maxStrings(const vector<string>& strs, int m, int n) {
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));  // dp[i][j]: best with i zeros, j ones
    for (const string& s : strs) {
        int zeros = count(s.begin(), s.end(), '0'), ones = (int)s.size() - zeros;
        for (int i = m; i >= zeros; i--)  // both capacities backwards: s is used once
            for (int j = n; j >= ones; j--)
                dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1);
    }
    return dp[m][n];
}
Java
class Solution {
    // Most strings you can pick with at most m zeros and n ones in total.
    int maxStrings(String[] strs, int m, int n) {
        int[][] dp = new int[m + 1][n + 1]; // dp[i][j]: best with i zeros, j ones
        for (String s : strs) {
            int zeros = (int) s.chars().filter(c -> c == '0').count(), ones = s.length() - zeros;
            for (int i = m; i >= zeros; i--) // both capacities backwards: s is used once
                for (int j = n; j >= ones; j--)
                    dp[i][j] = Math.max(dp[i][j], dp[i - zeros][j - ones] + 1);
        }
        return dp[m][n];
    }
}
Go
import "strings"

// maxStrings returns the most strings you can pick with at most m zeros and n ones.
func maxStrings(strs []string, m, n int) int {
	dp := make([][]int, m+1) // dp[i][j]: best with i zeros, j ones
	for i := range dp {
		dp[i] = make([]int, n+1)
	}
	for _, s := range strs {
		zeros := strings.Count(s, "0")
		ones := len(s) - zeros
		for i := m; i >= zeros; i-- { // both capacities backwards: s is used once
			for j := n; j >= ones; j-- {
				dp[i][j] = max(dp[i][j], dp[i-zeros][j-ones]+1)
			}
		}
	}
	return dp[m][n]
}
Bounded knapsack by binary splittingO(cap × Σ log cnt) time · O(cap) space

Item i has counts[i] copies: pack them in bundles of 1, 2, 4… plus the remainder and treat each bundle as one 0/1 item, cutting O(cap × Σcnt) to O(cap × Σlog cnt). It works for best value and feasibility; counting would count a quantity twice (5 = 1 + 2 + 2). No problem at this stop needs it directly; contests and OAs use it now and then.

Python
def bounded_knapsack(weights: list[int], values: list[int], counts: list[int], cap: int) -> int:
    """Best value within cap when item i has counts[i] copies."""
    dp = [0] * (cap + 1)
    for w, v, cnt in zip(weights, values, counts):
        k = 1
        while cnt > 0:  # bundles of 1, 2, 4, ... copies, then the rest
            take = min(k, cnt)
            cnt -= take
            k *= 2
            for c in range(cap, take * w - 1, -1):  # each bundle is one 0/1 item
                dp[c] = max(dp[c], dp[c - take * w] + take * v)
    return dp[cap]
C++
// Best value within cap when item i has counts[i] copies.
int boundedKnapsack(const vector<int>& weights, const vector<int>& values, const vector<int>& counts, int cap) {
    vector<int> dp(cap + 1, 0);
    for (size_t i = 0; i < weights.size(); i++) {
        int w = weights[i], v = values[i], cnt = counts[i];
        for (int k = 1; cnt > 0; k *= 2) {  // bundles of 1, 2, 4, ... copies, then the rest
            int take = min(k, cnt);
            cnt -= take;
            for (int c = cap; c >= take * w; c--)  // each bundle is one 0/1 item
                dp[c] = max(dp[c], dp[c - take * w] + take * v);
        }
    }
    return dp[cap];
}
Java
class Solution {
    // Best value within cap when item i has counts[i] copies.
    int boundedKnapsack(int[] weights, int[] values, int[] counts, int cap) {
        int[] dp = new int[cap + 1];
        for (int i = 0; i < weights.length; i++) {
            int w = weights[i], v = values[i], cnt = counts[i];
            for (int k = 1; cnt > 0; k *= 2) { // bundles of 1, 2, 4, ... copies, then the rest
                int take = Math.min(k, cnt);
                cnt -= take;
                for (int c = cap; c >= take * w; c--) // each bundle is one 0/1 item
                    dp[c] = Math.max(dp[c], dp[c - take * w] + take * v);
            }
        }
        return dp[cap];
    }
}
Go
// boundedKnapsack returns the best value within capacity when item i has counts[i] copies.
func boundedKnapsack(weights, values, counts []int, capacity int) int {
	dp := make([]int, capacity+1)
	for i, w := range weights {
		v, cnt := values[i], counts[i]
		for k := 1; cnt > 0; k *= 2 { // bundles of 1, 2, 4, ... copies, then the rest
			take := min(k, cnt)
			cnt -= take
			for c := capacity; c >= take*w; c-- { // each bundle is one 0/1 item
				dp[c] = max(dp[c], dp[c-take*w]+take*v)
			}
		}
	}
	return dp[capacity]
}

Why it works

  1. 0/1 knapsack loops capacity downwards: when dp[s] updates, dp[s−x] has not been touched this round and still excludes item x, so x is used at most once. Looping upwards, dp[s−x] may already include x, which reuses the item, exactly what the unbounded version wants.
  2. With items in the outer loop, each combination is counted once in item order, which counts combinations; with capacity outside, any item can be the last one at every step, so different orders count separately, which counts permutations. Coins {1, 2, 3} make 5 in 5 combinations but 13 orders.
  3. Target sum reduces to a knapsack: if the plus-signed numbers sum to P, then P − (sum − P) = target, so P = (sum + target) / 2, which also requires sum + target to be even and non-negative.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
背包问题我用一维数组 dp[s]。0/1 背包容量倒着循环,这样 dp[s − x] 还是没放这个物品时的值,每个物品最多用一次;完全背包正着循环,允许重复使用。计数时,物品在外层得到组合数,容量在外层得到排列数。很多题能归约成背包,比如分割等和子集就是问 sum/2 能不能凑出来。复杂度 O(n × 容量)。
English
For knapsacks I use a one-dimensional dp over capacity. The 0/1 version loops capacity downwards so dp[s − x] still excludes the current item, using each item at most once, and the unbounded version loops upwards to allow reuse. When counting, items in the outer loop count combinations and capacity in the outer loop counts permutations. Many problems reduce to this, for example equal-sum partition asks whether half the total is reachable, all in O(n × capacity).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. In one-row 0/1 knapsack, for w in range(W, wt - 1, -1): dp[w] = max(dp[w], dp[w - wt] + val). Why go from high capacity to low?
  2. Why is the O(n·W) 0/1 knapsack DP called pseudo-polynomial?
  3. coins = [1, 2], amount 3. Run ways = [1, 0, 0, 0]; for c in coins: for a in range(c, 4): ways[a] += ways[a - c]. What is ways[3]?
  4. items has n items and the capacity is W. What is the time complexity?
    def knapsack(items, W):
        dp = [0] * (W + 1)
        for wt, val in items:
            for w in range(W, wt - 1, -1):
                dp[w] = max(dp[w], dp[w - wt] + val)
        return dp[W]

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

def count_subsets(nums: list[int], target: int) -> int:
    return dp[amount]

Practice by stage

This stop's 10 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 7

#ProblemApproachRating
322Coin ChangeUse unbounded knapsack to minimize the number of choices, handling unreachable states and amount zero.
279Perfect SquaresGenerate square numbers as unbounded-knapsack items and recognize the minimum-count model from the problem statement.
518Coin Change IIIterate items in the outer loop to avoid counting permutations, explaining the loop order for combination counting.
377Combination Sum IVContrast this with Coin Change II and explain why iterating target sums first counts ordered sequences.
416Partition Equal Subset SumReduce equal partition to 0/1-knapsack reachability and explain descending capacities to prevent reusing elements.
494Target SumTransform sign assignments algebraically into subset counting, handling zeros and parity conditions.
1049Last Stone Weight IIReduce repeated collisions to minimizing the weight difference between two groups, abstracting the process into a subset problem.Rating 2092

Advanced 3

#ProblemApproachRating
474Ones and ZeroesApply 0/1 knapsack with two capacity dimensions and explain descending iteration and resource constraints.
879Profitable SchemesMerge all profits above the target into one state to practice counting with multiple constraints and bounded state ranges.Rating 2204
691Stickers to Spell WordRepresent the state by remaining character requirements or a bitmask, practicing memoization, deduplication, and impossibility detection.