Subsequences and knapsack
Subset and knapsack problems have the state (items considered, budget left). Each item is taken or skipped. In one dimension, loop the budget downwards when each item can be used once (0/1) and upwards when it can be reused (unbounded). Counting versions add, optimising versions take max or min, and possibility versions use OR.
How to recognise it
- Choose a subset with a given sum, or the best value under a weight limit.
- Coins, items or pieces that can be used once or many times.
- Split a set into two parts with a given difference.
Take it or leave it
0/1: for each item: for c from W down to w: best[c] = max(best[c], best[c - w] + v)
unbounded: for each item: for c from w up to W: best[c] = max(best[c], best[c - w] + v)
| Problem | Table | Combine |
|---|---|---|
| subset sum | can[s] | OR |
| count subsets with sum k | ways[s] | + |
| 0/1 knapsack | best[c] | max |
| coin change (fewest) | best[a] | min, unbounded |
| coin change II (ways) | ways[a] | +, unbounded, coins outer |
| rod cutting | best[len] | max, unbounded |
Turning a problem into subset sum
- Equal partition: reach total / 2.
- Partition with difference d: count subsets reaching (total - d) / 2.
- Target sum with signs: count subsets reaching (total + target) / 2.
- Last stone weight II: get one pile as close to total / 2 as possible.
Common mistakes
- Using the wrong loop direction.
- Forgetting zeros: each 0 doubles the number of subsets with a given sum.
Problems
- Subset sum equals to targetmediumguide ready
- Partition Equal Subset Summediumguide ready
- Last Stone Weight IImediumguide ready
- Count subsets with sum Kmediumguide ready
- Count partitions with given differencemediumguide ready
- 0 and 1 Knapsackmediumguide ready
- Coin Changemediumguide ready
- Target Summediumguide ready
- Coin Change IImediumguide ready
- Unbounded knapsackmediumguide ready
- Rod cutting problemmediumguide ready
- Count all subsequences having product less than Kmediumguide ready
- Minimum cost to fill given weight in a bagmediumguide ready
- Count number of ways to reacha given score in a gamemediumguide ready