39. Combination Sum
Asked at 26Bloomberg54Amazon53Microsoft49Google47Meta47Apple30HPE100Juniper Networks100Snap83Confluent72Yahoo71NetApp68ByteDance66Zomato62Walmart Labs60Airbnb60ServiceNow55Uber52TikTok50Citadel47Pinterest44Zoho42PayPal42Salesforce28LinkedIn27Oracle27
Problem
candidates are distinct positive integers. Return every unique combination that sums to target, where each candidate may be used any number of times. Two combinations differ if some number is used a different number of times.
Example: candidates = [2,3,6,7], target = 7 → [[2,2,3],[7]]
Constraints: up to 30 candidates; target ≤ 40.
Unlimited reuse → recurse with the same i. Sorting lets us break as soon as a candidate exceeds the remainder.
Complexity: exponential, bounded by O(n^(target/min)).
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
res, path = [], []
def bt(start, rest):
if rest == 0:
res.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > rest:
break
path.append(c)
bt(i, rest - c) # i: same number may be reused
path.pop()
bt(0, target)
return res
assert sorted(map(sorted, Solution().combinationSum([2, 3, 6, 7], 7))) == sorted(map(sorted, [[2, 2, 3], [7]]))
assert sorted(map(sorted, Solution().combinationSum([2, 3, 5], 8))) == sorted(map(sorted, [[2, 2, 2, 2], [2, 3, 3], [3, 5]]))
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res = new ArrayList<>();
bt(candidates, 0, target, new ArrayList<>(), res);
return res;
}
private void bt(int[] c, int start, int rest, List<Integer> path, List<List<Integer>> res) {
if (rest == 0) { res.add(new ArrayList<>(path)); return; }
for (int i = start; i < c.length && c[i] <= rest; i++) {
path.add(c[i]);
bt(c, i, rest - c[i], path, res);
path.remove(path.size() - 1);
}
}
}
func combinationSum(candidates []int, target int) [][]int {
sort.Ints(candidates)
res, path := [][]int{}, []int{}
var bt func(start, rest int)
bt = func(start, rest int) {
if rest == 0 {
res = append(res, append([]int{}, path...))
return
}
for i := start; i < len(candidates) && candidates[i] <= rest; i++ {
path = append(path, candidates[i])
bt(i, rest-candidates[i]) // i: the same number may be reused
path = path[:len(path)-1]
}
}
bt(0, target)
return res
}