Combination Sum (LeetCode 39): Solution and Explanation
Given an array of distinct positive integers and a target, list every unique combination of candidates whose values add up to the target. Any candidate may be used as many times as you like, and two combinations count as the same if they contain the same numbers with the same multiplicities, regardless of order.
Watch it run step by step
Try your own input and write the code →Intuition
A first instinct is to build sums by trying every candidate at every step. That finds all valid sums but produces duplicates such as [2,2,3], [2,3,2] and [3,2,2], because it treats order as meaningful. You would then have to sort and deduplicate, which wastes a lot of work.
The fix is to make choices in a fixed order so each combination can only be built one way. Walk through the candidates by index, and at each index make a single decision: either take candidates[i] one more time and stay at the same index, or decide you are finished with it and move to i + 1. Because you never go back to an earlier index, every combination is generated in non-decreasing index order exactly once.
This forms a binary decision tree. The left branch adds the current candidate and keeps the index, which is how unlimited reuse happens. The right branch moves past it for good. Since all candidates are positive, the running total only grows, so any branch whose total exceeds the target can be abandoned immediately, and any branch that hits the target exactly records a copy of the current combination.
Approach: Backtracking with include or skip decisions
- Create
resfor results and calldfs(0, [], 0), where the arguments are the current index, the current combination and its total. - If
total == target, append a copy ofcurtoresand return. - If
iis past the last candidate ortotalexceedstarget, return because this branch cannot succeed. - Include branch: append
candidates[i]tocurand recurse with the sameiand the larger total, so the same number can be used again. - Pop it back off
curto undo the choice. - Skip branch: recurse with
i + 1and the unchanged total, meaning this candidate is never used again on this path.
Step-by-step example
candidates = [2,3,6,7], target = 7
- Including 2 repeatedly builds [2], [2,2] and [2,2,2] with totals 2, 4 and 6. Adding a fourth 2 makes 8, which exceeds 7, so that branch stops.
- From [2,2,2], skipping to 3, 6 and 7 gives totals of 9, 12 and 13, all too large, and the index then runs out.
- Back at [2,2] with total 4, skipping 2 and including 3 gives a total of 7, so [2,2,3] is recorded.
- Other branches such as [2,3] (total 5) and [3,3] (total 6) cannot reach exactly 7 with the remaining larger candidates, so they all overshoot and stop.
- Skipping 2, 3 and 6 entirely and including 7 reaches 7, so [7] is recorded.
- The final result is [[2,2,3],[7]].
Code: Python, Java, C++
1class Solution:
2 def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
3 res = []
4
5 def dfs(i, cur, total):
6 if total == target:
7 res.append(cur.copy())
8 return
9 if i >= len(candidates) or total > target:
10 return
11
12 cur.append(candidates[i])
13 dfs(i, cur, total + candidates[i])
14 cur.pop()
15 dfs(i + 1, cur, total)
16
17 dfs(0, [], 0)
18 return res1class Solution {
2 public List<List<Integer>> combinationSum(int[] candidates, int target) {
3 List<List<Integer>> res = new ArrayList<>();
4 dfs(0, new ArrayList<>(), 0, candidates, target, res);
5 return res;
6 }
7
8 private void dfs(int i, List<Integer> cur, int total, int[] candidates, int target, List<List<Integer>> res) {
9 if (total == target) {
10 res.add(new ArrayList<>(cur));
11 return;
12 }
13 if (i >= candidates.length || total > target) {
14 return;
15 }
16
17 cur.add(candidates[i]);
18 dfs(i, cur, total + candidates[i], candidates, target, res);
19 cur.remove(cur.size() - 1);
20 dfs(i + 1, cur, total, candidates, target, res);
21 }
22}1class Solution {
2public:
3 vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
4 vector<vector<int>> res;
5 vector<int> cur;
6 dfs(0, cur, 0, candidates, target, res);
7 return res;
8 }
9
10 void dfs(int i, vector<int>& cur, int total, vector<int>& candidates, int target, vector<vector<int>>& res) {
11 if (total == target) {
12 res.push_back(cur);
13 return;
14 }
15 if (i >= candidates.size() || total > target) {
16 return;
17 }
18
19 cur.push_back(candidates[i]);
20 dfs(i, cur, total + candidates[i], candidates, target, res);
21 cur.pop_back();
22 dfs(i + 1, cur, total, candidates, target, res);
23 }
24};Time and space complexity
O(2^(n + t/m))
Here t is the target and m is the smallest candidate. Each step either adds a candidate, which can happen at most t/m times on a path, or advances the index, which can happen at most n times, so the binary decision tree has depth at most n + t/m. Copying each found combination adds a smaller extra cost.
O(n + t/m)
The recursion depth and the length of cur are bounded by the same path length, ignoring the space used by the output itself.
Other approaches
Loop-based backtracking from a start index (time O(n^(t/m)), space O(t/m))
At each call, loop j from the current start to the end, add candidates[j], and recurse with start j. Sorting the candidates first lets you break out of the loop as soon as a value exceeds the remaining target. It explores the same combinations with a shallower tree.
Dynamic programming over sums (time O(n × t × C), space O(t × C))
Build a table where entry s holds every combination summing to s, processing candidates in the outer loop so each combination is formed in one order. It avoids recursion but stores many partial lists, which can use a lot of memory. Here C stands for the number of combinations kept per sum.
Common mistakes
- Appending
curitself instead ofcur.copy(). Later pops would then change the stored result. - Advancing to
i + 1on the include branch, which prevents a candidate from being reused. - Looping over all candidates from index 0 at every level, which generates the same combination in several orders.
- Forgetting the
total > targetcheck, which leads to unbounded recursion along the include branch.
Frequently asked questions
How do you avoid duplicate combinations in Combination Sum?
Only move forward through the candidate list. Once you skip an index you never return to it, so each combination is built in a single canonical order and appears exactly once.
How is Combination Sum different from Combination Sum II?
Here each candidate can be reused without limit and all candidates are distinct. In the second version each number can be used once and the input may contain duplicates, so you sort and skip equal neighbors at the same depth.
Why does the include branch keep the same index?
Staying on the same index after taking a candidate lets you take it again on the next step. That is how the algorithm supports unlimited reuse without trying earlier candidates and creating reordered duplicates.