Exact Postage Stamps

MediumbacktrackingAlso known as Combination Sum

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

Example 1
Input
values = [2, 3, 5]
postage = 8
Output
[[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Why

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.

Example 2
Input
values = [4, 6]
postage = 9
Output
[]
Why

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

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.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code