You get a list of different positive whole numbers, candidates, and a number target. Pick numbers from the list so that they add up to target. Any candidate may be picked as many times as you like.
Return every different way to do it. Two picks are the same if they use each number the same number of times, so [2, 5] and [5, 2] count once. The combinations can come back in any order.
Example 1
Input: candidates = [3, 4, 5], target = 8 Output: [[3, 5], [4, 4]] Why: 3 + 5 = 8 and 4 + 4 = 8
2 more examples and the constraints
Example 2
Input: candidates = [2, 5, 3], target = 7 Output: [[2, 2, 3], [2, 5]] Why: 2 is used twice in the first one
Example 3
Input: candidates = [4, 6], target = 5 Output: [] Why: no mix of 4s and 6s makes 5
Constraints
- 1 ≤ length of candidates ≤ 30
- 2 ≤ each candidate ≤ 40, and no value appears twice
- 1 ≤ target ≤ 40
- There are fewer than 150 combinations for every input
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build up from smaller sumsO(n·T²·k)
- Backtracking with a start indexO(n^(T/c))
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for target 40 | Verdict |
|---|---|---|---|
| Build up from smaller sums | O(n·T²·k) | Passes; stores every sub-sum | |
| Backtracking with a start index | O(n^(T/c)) | Best; builds only what is needed |
n = number of candidates, T = target, c = smallest candidate, k = most combinations for one sum.
Edge cases to test
- No combination. [4, 6] with target 5 returns an empty list, not [[]].
- The target is a candidate. [7] with target 7 gives [[7]]: a combination of one number.
- One number many times. [2, 39] with target 40 needs twenty 2s.
- Every candidate too big. [5, 10] with target 3: the first loop breaks at once.
Common mistakes
- Starting every loop at index 0, which produces [2, 5] and [5, 2] as separate answers.
- Recursing with i + 1, which forbids reusing a candidate.
- Saving the path itself instead of a copy, so every saved entry changes as you backtrack.
How to talk through it
- 1Clarify. Are the candidates distinct and positive? Does the order inside a combination or of the list matter?
- 2Name the duplicate problem. Picking freely gives every order of the same mix; fix the order by never going back to an earlier index.
- 3Describe the search. Choose a candidate, recurse with the same index and a smaller remainder, undo the choice.
- 4Code it with pruning. Sort first so the loop can break at the first candidate bigger than the remainder.
- 5Test out loud. Run a target no mix can make, a target equal to a candidate, and one that needs many copies of one number.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?