Combination Sum

Medium#39pick with repeats

You get a list of different positive numbers, the candidates, and a target. Return every combination of candidates that adds up to the target, where a candidate may be used any number of times; two combinations with the same numbers in another order count as one. Our example: [4, 5, 3] and 8 give [3, 5] and [4, 4].

input
candidates: an array of different integers; target: an integer.
returns
Every combination of numbers from candidates that adds up to target; a number may be taken any number of times. Two combinations are the same when they hold the same numbers, each as many times: give each one once. Combinations in any order, numbers in a combination too.
constraints
  • 1 ≤ candidates.length ≤ 30
  • 2 ≤ candidates[i] ≤ 40
  • all the numbers of candidates are different
  • 1 ≤ target ≤ 40
  • fewer than 150 combinations add up to target
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
function combinationSum(candidates, target) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more backtracking problems

Pattern “Backtracking” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.