Bank app~20 min2s · 256 MBtarget O(calls × n) time, O(total) spaceclassic twin: lc-39backtracking
A bank app helps a small shop take an exact payment. The shop has a price list, and a customer may buy any item more than once.
The customer enters an amount in units. The app lists every way to choose items so that their prices add up to exactly that amount.
Your team lead says: List every combination of items for the amount, and list each one once.
Write invoice_combinations(prices, total).
total. A combination has at least one price.total.Input: prices = [4, 6, 3], total = 12
Output: [[3, 3, 3, 3], [3, 3, 6], [4, 4, 4], [6, 6]]The prices sorted are 3, 4, 6. A call may choose the same price again, so the next call starts at the same position.
| Combination | Calls made so far when it is saved |
|---|---|
| [3, 3, 3, 3] | 5 |
| [3, 3, 6] | 7 |
| [4, 4, 4] | 13 |
| [6, 6] | 16 |
The search makes 16 calls. The answer has 4 combinations.
Input: prices = [5, 8], total = 3
Output: []Neither 5 nor 8 fits into 3, so the loop is cut at once. The answer is an empty list.
Input: prices = [2], total = 6
Output: [[2, 2, 2]]The price 2 is used three times. A price may be used again, so [2, 2, 2] is one combination.
1 ≤ prices.length ≤ 302 ≤ prices[i] ≤ 300, and the prices are different from one another1 ≤ total ≤ 300A price may be used up to total ÷ price times, so the first attempt tries more than 10^19 count lists for the first large test. The search stays small because the bound cuts every price that is too large. It makes 458,560 calls and finds 14,184 combinations. The recursion is at most 150 calls deep, because the smallest price is 2.