Counting Combinations
In the previous lesson, order mattered: 1+2 and 2+1 were two patterns. Often it doesn't: a crate holding a 2 kg box and a 3 kg box is the same crate whichever went in first. Counting combinations needs a recursion that can't produce the same set twice.
Decide one weight at a time
Line up the weights and make one decision at a time about the first weight still in play:
- take no more of it, and move on to the next weight; or
- take one more of it, and stay on the same weight (you may take another).
ways(i, left) = ways(i+1, left) skip weights[i]
+ ways(i, left - weights[i]) one more weights[i]
Because each weight is decided before the next, a combination is always built in the same order, so it's counted exactly once. The base cases: left == 0 means the crate is exactly full, one way; running out of weights with left > 0 means zero ways.
For "at most one of each", the only change is the second line: after taking weights[i], move on to i+1.
A struct as the memo key
The answer now depends on two numbers, i and left. A map key can be any comparable type, so put both in a small struct:
type state struct {
i, left int
}
memo := map[state]int{}
state{2, 15} and state{2, 15} are equal, so the second time the recursion asks the same question it finds the answer in the map. The number of different states is at most len(weights) × (total + 1), which is the most work the memoised recursion can do.
When the answer depends on more things (a position, a direction, keys collected so far), add them to the struct. Thinking "what exactly does the rest of the answer depend on?" is the heart of dynamic programming.
Task
This lesson's input gives the crate size and the box weights. The weights are all different and at least 1.
- Complete
combos(weights []int, total int) int: how many ways boxes fill the crate to exactlytotalkg, with any number of boxes of each weight. Order doesn't matter. - Complete
combosEachOnce(weights []int, total int) int: the same, with at most one box of each weight.
An empty crate (total == 0) can be filled in exactly one way: no boxes. The tests use totals up to 1,000, so remember your answers.