Combination Sum

Medium Backtracking

candidates is a list of different whole numbers, and target is a whole number.

A combination is some numbers from candidates that add up to target, each number used as many times as you like. Two combinations are the same when they hold the same numbers, each as many times, in whatever order.

Return every combination, each exactly once, or an empty list when there is none. The combinations may come in any order, and so may the numbers inside each one.

Example 1

Input: candidates = [6,4,9], target = 12
One right answer: [[4,4,4],[6,6]]

4 used three times makes 12, and so does 6 used twice. No combination holds 9: it leaves 3, which no number here makes.

Example 2

Input: candidates = [2,7,3], target = 10
One right answer: [[2,2,2,2,2],[2,2,3,3],[3,7]]

Example 3

Input: candidates = [5,8], target = 3
One right answer: []

Constraints

  • 1 ≤ candidates.length ≤ 39
  • 2 ≤ candidates[i] ≤ 40
  • All the numbers in candidates are different
  • 1 ≤ target ≤ 40
  • The largest answer, for target 40 with every number from 2 to 40, has 6,153 combinations

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Backtracking

All Backtracking problems