Knapsack problem
There are n items, each with a weight and a value, and a knapsack with capacity cap. You want the highest total value without going over the capacity, and each item can be taken at most once: that is why it is called 0-1. It is a sequence of n decisions, skip or take, so it fits a decision tree. With capacity 4 and items of weight 1, 2 and 3 worth 5, 11 and 15, the best is to take the weight-1 and weight-3 items: value 20.
Skipping an item does not change the free capacity; taking it shrinks it. That is why the state has 2 variables: the item number i and the free capacity c, [i, c]. dp[i, c] is the highest value with the first i items and a knapsack of capacity c. The answer is dp[n, cap], and the table has (n + 1) Γ (cap + 1) cells: with 3 items and capacity 4, 4 Γ 5 = 20.
Since each row only uses the previous one, 2 lists are enough, and memory goes from O(n Γ cap) to O(cap). You can even use a single list, but walking the capacities from largest to smallest. If you walk from smallest to largest, the value above and to the left has already been overwritten with the new row's, and an item gets counted twice. Example: an item of weight 1 and value 5, capacity 2. Going forward, dp[2] = dp[1] + 5 = 10; going backward, it gives 5, which is correct.
