Exact Postage Stamps

MediumbacktrackingAlso known as Combination Sum

A village post office sells stamps in a handful of values and has plenty of each. Every parcel needs postage that adds up to exactly the price on the scale: one coin short and it comes back, one coin over and the customer complains.

The clerk wants to see every way to make a given price from the stamp values, so she can choose the one that uses up old stock. The order the stamps are stuck on does not matter: a 2, a 3 and a 3 is the same set as a 3, a 2 and a 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, so do 2 + 3 + 3 and 3 + 5. Sets like 3 + 3 + 2 are not listed again: they hold the same stamps as [2, 3, 3]. 5 + 2 leaves 1 to go, and no stamp is worth 1.

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

4 and 6 are both even, so any sum of them is even and can never be 9. No set works, so the answer is an empty list.

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

Keep adding any stamp in any order until the total reaches or passes the postage, then sort each successful list and use a set to drop duplicates. It finds every answer, but each answer is built once for every order its stamps can be stuck on: [2, 2, 3, 3] alone is built 6 times.

With many small values the number of orders explodes far faster than the number of answers. For values 1 to 10 and postage 12 there are only 75 different sets, but 2,045 ordered ways to reach 12, and the gap widens quickly as the postage grows.

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