Exact Change Stacks
Medium · Backtracking · about 20 min
A ticket machine pays change using coin values from coins (distinct positive integers) and has an unlimited supply of each value. List every different way to pay exactly amount.
- Write each way as its coins sorted ascending, for example
[2, 2, 3]. The order coins are dropped in does not matter, so[2, 3, 2]is the same way and must not appear. - Return the ways sorted the way Python sorts lists (compare item by item).
- Return
[]if there is no way. - 1 to 8 coins, each 1 to 40, in any order; 1 ≤
amount≤ 40.
change_stacks([2, 3, 5], 8) → [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
Hints
- Sort the coins. Write a helper that knows how much is left and which coin position it may start from.
- After adding a coin, recurse starting from that same coin so it can be used again, but never from an earlier one.
- When nothing is left, record a copy of the stack. When a coin is bigger than what is left, stop trying coins.
Learn the pattern first: the Backtracking lesson.
More Backtracking problems
- Every Snack Bundle (Easy)
- Every Seating Plan (Easy)
- Keypad Spellings (Easy)
- Distinct Gift Bags (Medium)
- Trace a Word on the Letter Board (Medium)
- Mirror Word Splits (Medium)
- Peaceful Queens Count (Hard)