Skip to content

Combination Sum

MediumPython 3BacktrackingRecursionArrays

You are given a list of distinct positive integers candidates and a positive integer target. Return every unique combination of candidates whose values sum to target. The same candidate may be used any number of times. Two combinations are the same if they use the same multiset of numbers, regardless of order — return each combination once. Combinations may be returned in any order, and numbers within a combination in any order.

Constraints:
  - 1 <= len(candidates) <= 30
  - 2 <= candidates[i] <= 40, all distinct
  - 1 <= target <= 40
Examples:
  candidates = [2, 3, 6, 7], target = 7 -> [[2, 2, 3], [7]]
  candidates = [2, 3, 5], target = 8    -> [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
  candidates = [2], target = 1          -> []

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…