Blind 75
40 / 75Free practice

Combination Sum

Medium · Backtracking

Jump to code

Given distinct positive integers and a nonnegative target, return all value combinations summing to the target. Each value can be reused; combinations differing only in order are the same.

Examples

Example 1

candidates = [2,3,6,7]
target = 7

Output: [[2,2,3],[7]]

Example 2

candidates = [2,3,5]
target = 8

Output: [[2,2,2,2],[2,3,3],[3,5]]

Constraints

  • All elements of candidates are distinct.
  • 1 <= candidates.length <= 20
  • 2 <= candidates[i] <= 30
  • 2 <= target <= 30
Need a hint?

Never move backward in the candidate order while building one combination.

Asked in real interviews

Candidates reported versions of Combination Sum from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 8 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    2,
    3,
    6,
    7
  ],
  7
]
Expected
[
  [
    2,
    2,
    3
  ],
  [
    7
  ]
]
Case 2
Input
[
  [
    2,
    3,
    5
  ],
  8
]
Expected
[
  [
    2,
    2,
    2,
    2
  ],
  [
    2,
    3,
    3
  ],
  [
    3,
    5
  ]
]
Case 3
Input
[
  [
    2
  ],
  1
]
Expected
[]
Case 4
Input
[
  [
    3,
    4,
    5
  ],
  9
]
Expected
[
  [
    3,
    3,
    3
  ],
  [
    4,
    5
  ]
]
Case 5
Input
[
  [
    5,
    10
  ],
  3
]
Expected
[]

Drafts are saved per language in this browser when storage is available.