Practice · Backtracking · 3 of 4

Combinations That Add Up

You are given candidates, a list of distinct positive integers, and a positive integer target. Return every combination of candidates that adds up to exactly target. You may use each candidate as many times as you like.

Two combinations are the same if they use every candidate the same number of times, so [2, 3] and [3, 2] are one combination: list each combination once. The combinations, and the numbers inside each one, may come in any order. If nothing adds up to target, return an empty list.

Example 1

Input
candidates = [2, 3, 5, 9], target = 9
Output
[[9], [2, 2, 5], [2, 2, 2, 3], [3, 3, 3]]
9 on its own, 2 + 2 + 5, 2 + 2 + 2 + 3 and 3 + 3 + 3. Using a candidate more than once is allowed.

Example 2

Input
candidates = [3, 4, 7], target = 10
Output
[[3, 7], [3, 3, 4]]

Example 3

Input
candidates = [4], target = 3
Output
[]
The only candidate is already more than the target.

Constraints

  • candidates holds 1 to 30 distinct numbers, each between 2 and 40.
  • 1 ≤ target ≤ 40
  • The answer holds fewer than 150 combinations.
Brush up firstSubsets visualiser