Payments app~20 min2s · 256 MBtarget O(2^n) time, O(n) spaceclassic twin: lc-40backtracking
A payments app settles its fees at the end of each day. Each pending fee has an amount in units. The ledger team wants every set of fees that adds up to exactly the settlement amount, so they can match each set against a bank transfer.
Two fees with the same amount are interchangeable, so a set of amounts is listed once.
Your team lead says: Give me every set of amounts, and do not list one twice.
Write fee_combinations(fees, target).
target.Input: fees = [4, 2, 3, 2, 5], target = 7
Output: [[2, 2, 3], [2, 5], [3, 4]]The fees sorted are 2, 2, 3, 4, 5. The search takes one fee at a time, and stops a loop at a fee that is larger than what is left.
| Take | Chosen fees | Left to settle | What happens next |
|---|---|---|---|
| 2 | [2] | 5 | tries 2, 3, 4 and 5 after the first 2 |
| 2 | [2, 2] | 3 | tries 3, then 4 is cut |
| 3 | [2, 2, 3] | 0 | saves [2, 2, 3] |
| 3 | [2, 3] | 2 | 4 is more than 2, so 4 and 5 are cut |
| 4 | [2, 4] | 1 | 5 is more than 1, so it is cut |
| 5 | [2, 5] | 0 | saves [2, 5] |
| 3 | [3] | 4 | tries 4 |
| 4 | [3, 4] | 0 | saves [3, 4] |
| 4 | [4] | 3 | 5 is more than 3, so it is cut |
| 5 | [5] | 2 | no fee is left after 5 |
The second 2 at the top is skipped, because the first 2 already made every combination that starts with 2. The search made 11 calls. The answer is [[2, 2, 3], [2, 5], [3, 4]].
Input: fees = [3, 3, 3], target = 6
Output: [[3, 3]]Three equal fees give one combination of amounts: [3, 3]. Choosing different pairs of the three fees does not add a new combination.
Input: fees = [5, 6], target = 4
Output: []No combination of 5 and 6 adds up to 4, so the answer is an empty list.
1 ≤ fees.length ≤ 401 ≤ fees[i] ≤ 5001 ≤ target ≤ 5,000With 40 fees there are 1,099,511,627,776 subsets, so trying every subset takes far too long. The recursion must reject a partial set as soon as it passes target. The first large test makes 554,858 calls and finds 7,079 combinations. A search of depth 40 is safe for the call stack.