Combination Sum
Medium · Backtracking
Jump to codeGiven 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 questionsSolution approach
Sort candidates. Recurse with a start index, remaining total, and current path. Try values from start onward, stopping when a value exceeds the remainder. Recurse with the same index to allow reuse. Copy the path at remainder zero, then backtrack.
Complexity
Output-sensitive exponential time; O(target / smallest candidate) recursion depth, plus output and sorting space.
Python reference solution
def combinationSum(candidates, target):
candidates = sorted(candidates)
answer, path = [], []
def search(start, remaining):
if remaining == 0:
answer.append(path.copy())
return
for i in range(start, len(candidates)):
value = candidates[i]
if value > remaining:
break
path.append(value)
search(i, remaining - value)
path.pop()
search(0, target)
return answer
JavaScript solution
function combinationSum(candidates, target) {
candidates.sort((a, b) => a - b);
const answer = [], path = [];
function search(start, remaining) {
if (remaining === 0) { answer.push([...path]); return; }
for (let i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) break;
path.push(candidates[i]);
search(i, remaining - candidates[i]);
path.pop();
}
}
search(0, target);
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[][] combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<int[]> answer = new ArrayList<>();
search(candidates, 0, target, new ArrayList<>(), answer);
return answer.toArray(new int[0][]);
}
private void search(int[] candidates, int start, int remaining,
List<Integer> path, List<int[]> answer) {
if (remaining == 0) {
answer.add(path.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] > remaining) break;
path.add(candidates[i]);
search(candidates, i, remaining - candidates[i], path, answer);
path.remove(path.size() - 1);
}
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int> &candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> answer;
vector<int> path;
function<void(int, int)> search = [&](int start, int remaining) {
if (remaining == 0) { answer.push_back(path); return; }
for (int i = start; i < (int)candidates.size(); i++) {
if (candidates[i] > remaining) break;
path.push_back(candidates[i]);
search(i, remaining - candidates[i]);
path.pop_back();
}
};
search(0, target);
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
2,
3,
6,
7
],
7
][
[
2,
2,
3
],
[
7
]
][
[
2,
3,
5
],
8
][
[
2,
2,
2,
2
],
[
2,
3,
3
],
[
3,
5
]
][
[
2
],
1
][]
[
[
3,
4,
5
],
9
][
[
3,
3,
3
],
[
4,
5
]
][
[
5,
10
],
3
][]
Drafts are saved per language in this browser when storage is available.