Learn / Dynamic programming

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)
ProblemTableCombine
subset sumcan[s]OR
count subsets with sum kways[s]+
0/1 knapsackbest[c]max
coin change (fewest)best[a]min, unbounded
coin change II (ways)ways[a]+, unbounded, coins outer
rod cuttingbest[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

0 of 14 solved

Check yourself

Why loop capacity downwards in 0/1 knapsack with one array?

Coin Change II counts combinations. Why are coins the outer loop?

Partition into two subsets of equal sum is which question?

Target Sum with signs + and - reduces to?