☰ All problems

67. Combination Sum

MediumArrayBacktracking

Given an array of distinct positive integers candidates and a positive integer target, return every unique combination of candidates whose sum is exactly target.

Any candidate may be used as many times as you like. Two combinations are the same if they use each number the same number of times, so [2,3,3] and [3,2,3] count once. Return the combinations in any order; the numbers inside a combination may also be in any order. If no combination works, return an empty list.

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

Explanation: 3 + 5 = 8 and 4 + 4 = 8; the 4 is reused.

Example 2
Input: candidates = [2,3], target = 6
Output: [[2,2,2],[3,3]]
Example 3
Input: candidates = [2], target = 1
Output: []

Constraints

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 40
  • All values in candidates are distinct
  • 1 <= target <= 40
  • Every test has fewer than 150 valid combinations

Follow-up: Now each candidate may be used at most once and candidates may contain duplicates. How do you still avoid repeated combinations?

💡 Hint 1

To avoid producing the same combination in different orders, only ever pick candidates at or after the index of the last one you picked.

💡 Hint 2

Backtrack with (start, remaining): for each i >= start, choose candidates[i] and recurse with (i, remaining - candidates[i]). Passing i (not i + 1) allows reuse.

💡 Hint 3

Sort the candidates first so you can stop the loop as soon as a candidate exceeds remaining.

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
function combinationSum(candidates, target) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc