DSAPrep
MediumBacktracking

Combination Sum

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation: 2 and 3 are candidates, and 2 + 2 + 3 = 7 (2 can be reused). 7 is a candidate, and 7 = 7. These are the only two combinations.

Example 2

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3

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

Constraints

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • All elements of candidates are distinct.
  • 1 <= target <= 40
View original on LeetCode ↗

Because each number can be reused, this is not a simple “include or exclude” subset problem — at every step we choose how many more times to use the current candidate (including zero) before moving on to the next one.

Brute Force: Generate-and-Filter

Time exponentialSpace exponential

Recurse over “use candidate i, or don’t” like Subsets, but allow re-using an index unboundedly, and only check the sum against target once a full combination is built. Without pruning on the running sum, this explores far more branches than necessary — for example it keeps recursing even after the partial sum has already exceeded target.

class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
result = []
path = []
def backtrack(start, path_sum):
if path_sum == target:
result.append(path[:])
return
if start == len(candidates):
return
# option 1: use candidates[start] again
if path_sum + candidates[start] <= target:
path.append(candidates[start])
backtrack(start, path_sum + candidates[start])
path.pop()
# option 2: move on to the next candidate
backtrack(start + 1, path_sum)
backtrack(0, 0)
return result

This already has the path_sum <= target check, otherwise it degenerates into infinite recursion (reusing a positive number forever). Even with it, branching into “use again” and “skip” at every node explores overlapping work that the loop-based version below avoids.

Backtracking with a For-Loop and Pruning

OptimalTime O(n^(t/m + 1))Space O(t/m)

Sort the candidates first. At each recursive call, loop over candidates starting from the current index (allowing the same index to be reused on the next call), and stop the loop as soon as a candidate exceeds the remaining budget — since the array is sorted, everything after it is too large as well.

class Solution:
def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
candidates.sort()
result = []
path = []
def backtrack(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
if candidates[i] > remaining:
break # sorted, so nothing further can fit either
path.append(candidates[i])
backtrack(i, remaining - candidates[i]) # i, not i+1: reuse allowed
path.pop()
backtrack(0, target)
return result

Tracing candidates = [2,3,6,7], target = 7 (sorted already) as a decision tree, where each node is a partial sum and a branch is discarded once it would overshoot:

0
1 / 6
resultcurrentdiscarded

Start at sum 0, remaining target 7. Try candidates from index 0 onward.

Complexity: in the worst case (candidates like [1] with a large target) the recursion depth is t/m where m is the smallest candidate, and each level branches over n candidates, giving O(n^(t/m + 1)) time; the recursion stack and path are bounded by that same depth → O(t/m) space. Sorting first lets the break prune entire subtrees early rather than visiting every combination that overshoots.