Combination Sum

MediumBacktracking

You get an array of different positive integers candidates and a positive target. Return every combination of candidates that adds up to target. A candidate can be used any number of times.

Two combinations are the same if they use the same numbers the same number of times, so list each one once. The combinations can come back in any order, and so can the numbers inside each.

Examples

Example 1
Input:  candidates = [3, 4, 5], target = 8
Output: [[3, 5], [4, 4]]

3 + 5 = 8 and 4 + 4 = 8. Using 4 twice is allowed.

Example 2
Input:  candidates = [5, 7], target = 3
Output: []

Every candidate is bigger than 3, so nothing adds up to it.

Constraints

  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40, all different
  • 1 ≤ target ≤ 40

Stuck?

Hint 1

Build a combination one number at a time and backtrack: add a candidate, solve for the smaller target that is left, then take it back off.

Hint 2

To stop [2, 3] and [3, 2] both turning up, let each call pick only from the candidate it is on and the ones after it. Passing the same index down is what lets a number repeat.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur