Exact Postage Stamps
A village post office has plenty of stamps in a handful of values. Postage must add up to exactly the price on the scale, and the clerk wants every way to make it, so she can pick the one that uses up old stock. Stamp order does not matter: 2, 3, 3 is the same set as 3, 2, 3.
Your task
Write stampSets(values, postage). values lists the different stamp values, and each value can be used any number of times. Return every different set of stamps whose values add up to exactly postage.
Write each set as a list of stamp values in non-decreasing order, like [2, 3, 3]. The sets themselves can be in any order. If no set works, return an empty list. For postage = 0 the only set is the empty one: return [[]].
stampSets(values: int[], postage: int) → int[][] Any order of the returned list is accepted.
Examples
values = [2, 3, 5] postage = 8
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Four 2s make 8, as do 2 + 3 + 3 and 3 + 5. 3 + 3 + 2 is not listed again because it is the same set as [2, 3, 3]. Using 5 and 2 leaves 1, and no stamp is worth 1.
values = [4, 6] postage = 9
[]
4 and 6 are even, so every sum is even and can never be 9.
Constraints
- 1 ≤ values.length ≤ 10
- 1 ≤ values[i] ≤ 50, all different, in any order
- 0 ≤ postage ≤ 60
- The answer contains at most 300 sets.
Start with brute force
Add any stamp in any order until the total reaches or passes the postage, then sort each hit and drop duplicates with a set. It finds every answer, but builds each one once per ordering: [2, 2, 3, 3] alone is built 6 times. The number of orderings grows much faster than the number of answers. With values 1 to 10 and postage 12 there are only 75 sets but 2,045 ordered ways.
Hints
0 of 4 shown- Hint 1
Take stamps worth 2 and 3 and postage 7. Is 2 + 2 + 3 a different answer from 3 + 2 + 2? How could you avoid building both?
- Hint 2
Pick stamps in a fixed order: after a value, you may only pick that value or a larger one. Then each set has exactly one way to be built.
- Hint 3
Sort the values. Write a recursive helper
pick(start, remaining)that tries each value from positionstarton. After choosing positioni, callpick(i, remaining − values[i]): the samei, because a stamp may be reused. - Hint 4
When
remainingis 0, record a copy of the current set. Since values are sorted, once one is larger thanremaining, so is every later one: stop the loop. Push before the call, pop after it.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
Duplicates appear when the same set is built in different orders. Instead of removing them afterwards, the search prevents them by only picking values in non-decreasing order.
The trace below uses values [2, 3, 5] and postage 8.
- The search picks 2 four times, which leaves 0 remaining, so it records
[2, 2, 2, 2]. - It goes back to
[2, 2]with 4 remaining. Picking 3 leaves 1, and no value fits, so that branch ends. The value 5 is bigger than 4, so the loop stops. - It goes back to
[2]with 6 remaining. Picking 3 and then 3 again reaches 0, so it records[2, 3, 3]. Picking 5 leaves 1, which cannot be filled. - It goes back to the empty set and starts with 3, since 2 is no longer allowed. Picking 3 twice leaves 2, and no value from 3 upward fits. Picking 3 and then 5 reaches 0, so it records
[3, 5]. - Starting with 5 leaves 3, and 5 is too big to pick again, so the search ends.
There are two common mistakes. Recursing with i + 1 lets each stamp be used at most once, so [2, 2, 2, 2] is lost. Recursing with 0 builds every ordering again, which produces duplicates such as [3, 2, 3].
function stampSets(values, postage) {
const sorted = [...values].sort((a, b) => a - b);
const sets = [];
const current = [];
function pick(start, remaining) {
if (remaining === 0) {
sets.push([...current]); // exact postage reached
return;
}
for (let i = start; i < sorted.length; i++) {
if (sorted[i] > remaining) break; // later values are too big too
current.push(sorted[i]);
pick(i, remaining - sorted[i]); // i, not i + 1: reuse allowed
current.pop();
}
}
pick(0, postage);
return sets;
}def stamp_sets(values, postage):
values = sorted(values)
sets = []
current = []
def pick(start, remaining):
if remaining == 0:
sets.append(current[:]) # exact postage reached
return
for i in range(start, len(values)):
if values[i] > remaining:
break # sorted, so later values are too big too
current.append(values[i])
pick(i, remaining - values[i]) # i, not i + 1: reuse allowed
current.pop()
pick(0, postage)
return setsRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.