Combinations That Reach a Target
You get an array candidates of different positive integers and a positive integer target.
You can use each candidate as many times as you want. Return every combination of candidates whose sum is exactly target. Two combinations are different if some number is used a different number of times. Do not return the same combination twice.
Output order
- Write the numbers inside each combination in non-decreasing order. For example, write
[2, 2, 5], not[5, 2, 2]. - Sort the list of combinations from smallest to largest. To compare two combinations, look at the first position where they differ; the one with the smaller number there comes first. So
[2, 2, 5]comes before[2, 7], because2 < 7at the second position.
If no combination works, return an empty array []. The candidates array is not sorted.
Hint
Sort the candidates first. Build a combination one number at a time. After you add the candidate at index i, the next number may only come from index i or later. This stops [2, 3] and [3, 2] from both appearing, and it produces the combinations already in the required order. Stop early when a candidate is larger than what is left of the target.
Examples
Example 1
- Input:
- [5,2,7], 9
- Output:
- [[2,2,5],[2,7]]
2 + 2 + 5 = 9 and 2 + 7 = 9. No other mix of 2, 5 and 7 adds up to 9. [2, 2, 5] comes first because 2 < 7 at the second position.
Example 2
- Input:
- [3,4], 12
- Output:
- [[3,3,3,3],[4,4,4]]
Four 3s make 12, and three 4s make 12. A mix such as 3 + 3 + 4 = 10 or 3 + 4 + 4 = 11 does not reach 12.
Example 3
- Input:
- [4,6,10], 7
- Output:
- []
Every candidate is even, so every sum is even. 7 cannot be reached.
Constraints
1 <= candidates.length <= 62 <= candidates[i] <= 30, and all values incandidatesare different.1 <= target <= 30- The answer has at most 12 combinations.
Run checks your code against the 3 examples. Submit checks it against all 163 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.