Combination Sum

MediumBacktracking

You are given an array of distinct positive integers candidates and a positive integer target. Return every combination of candidates whose sum equals target.

Each candidate may be used any number of times in a combination. Two combinations are the same if they use the same candidates the same number of times, whatever the order, so [2, 2, 3] and [3, 2, 2] count once. Return each distinct combination once, in any order, with its numbers in any order. If no combination works, return an empty array.

Constraints

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 40, all distinct
  • 1 <= target <= 40
  • There are fewer than 150 valid combinations.

Examples

Example 1

Input: candidates = [3,4,5], target = 11
Output: [[3,4,4],[3,3,5]]

3 + 3 + 5 = 11 and 3 + 4 + 4 = 11. A candidate may be reused, but [3, 5, 3] is the same combination as [3, 3, 5] and must appear only once.

Example 2

Input: candidates = [7], target = 3
Output: []

The only candidate is already larger than the target, so no combination exists.

Example 3

Input: candidates = [1], target = 2
Output: [[1,1]]

The same candidate may be used more than once: 1 + 1 = 2.

JavaScript you'll use: Recursion, the call stack and memoization Sorting and comparators Arrays: create, read, update

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

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.