15% off all plans & roadmaps Use code
See plansCombination Sum
- LeetCode 39
- Medium
- Backtracking Patterns
- Combination Sum
Updated
TL;DR: Find every multiset of distinct numbers, each reusable any number of times, that adds up to the target. Backtracking with a start index builds each combination in non-decreasing index order, so no duplicates appear, and sorting lets you stop a loop early.
Problem
You are given an array candidates of distinct integers and an integer target. Return a list of all unique combinations of candidates whose chosen numbers add up to target. The combinations may be returned in any order.
You may use the same number from candidates as many times as you like. Two combinations are different if at least one number appears a different number of times in them.
The tests are built so that the number of unique combinations summing to target is less than 150 for every input.
Example 1
Input: candidates = [2,3,6,7], target = 7 Output: [[2,2,3],[7]] Explanation: 2 + 2 + 3 = 7, and 2 is used twice. Also 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 <= 302 <= candidates[i] <= 40- All elements of
candidatesare distinct. 1 <= target <= 40
Constraints that matter
target <= 40andcandidates[i] >= 2cap the length of any combination at 20 numbers. That keeps recursion depth tiny, so recursion is safe in every language.- Fewer than 150 answers are guaranteed. Output size is small, so the cost is dominated by how many dead-end branches you explore, and pruning is what matters.
- All values are positive. The running sum only grows, so once it passes
targetyou can abandon that branch for good. With zero or negative values this would not hold. - Candidates are distinct. You never need to skip equal neighbours to avoid duplicate answers, which is the main difference from Combination Sum II.
candidates.length <= 30rules out any approach that tries all 2^30 subsets blindly, but it does not rule out a pruned search.
Hints
Hint 1
This is backtracking.
Hint 2
Walk through the candidates in order and, for each one, decide how many copies to include, from the maximum that fits down to zero.
Solution
Intuition
This is backtracking. You build an answer one number at a time, check whether you hit the target, and undo the last choice to try the next one. The search tree has one level per number added, and the positive values let you cut any branch whose sum already exceeds target.
It is like shopping from a price list sorted cheapest to most expensive with a fixed budget. The sorted array is the price list, the remaining sum rem is what is left in your wallet, and the break is the moment you stop reading because the current item already costs more than you have.
The detail that decides everything is how to avoid counting [2, 2, 3] and [2, 3, 2] as two answers. The fix is to impose an order. After you pick candidates[i], you may pick candidates[i] again or anything to its right, but never anything to its left. Each multiset then has exactly one path in the tree, the one that lists its numbers in index order.
Reuse comes from passing i instead of i + 1 into the recursive call. Duplicate prevention comes from starting the loop at start instead of 0. Those two small choices are the whole algorithm.
Sorting adds one more cut. If candidates is sorted ascending and candidates[i] is already larger than the remaining sum, every later candidate is larger too. You can break out of the loop instead of testing each one.
Worked example
Input: candidates = [2, 3, 6, 7], target = 7 Output: [[2, 2, 3], [7]] Explanation: Using 2 twice and 3 once gives 2 + 2 + 3 = 7. Using 7 once gives 7. Every other mix, such as 2 + 2 + 2 + 1 or 3 + 3 + 1, either overshoots or cannot hit 7 exactly. Order inside a combination does not matter, so [2, 3, 2] is the same answer as [2, 2, 3].
Approach 1: Brute force: choose a count for every candidate
Walk through the candidates in order and, for each one, decide how many copies to include, from the maximum that fits down to zero. At the end of the list, check whether the remaining sum is exactly zero. Every multiset is produced once because each candidate gets one count, so no deduplication step is needed.
This is the plain "try every option" search. It does not use any ordering trick beyond the fixed candidate order, and it keeps descending to the end of the array even when nothing is left to place.
Steps
- Define
choose(i, rem, path)whereiis the candidate being decided andremis the sum still needed. - If
rem == 0, record a copy ofpathand return, since all later candidates must get count zero. - If
iequals the number of candidates, return, becauseremis still positive and nothing is left to add. - Let
c = candidates[i]. Forkfromrem / cdown to 0, appendkcopies ofctopath. - Recurse with
choose(i + 1, rem - k * c). - Remove the
kcopies you added, then try the next smallerk. - Call
choose(0, target)and return the recorded list.
Dry run
Candidates [2, 3, 6, 7], target 7. Counts are tried from high to low.
- Candidate 2 can appear up to 3 times. Take k=3, path [2,2,2], rem 1. Candidates 3, 6, 7 all get count 0, the list ends with rem 1, so this branch fails.
- Take k=2, path [2,2], rem 3. Candidate 3 with k=1 gives [2,2,3] and rem 0, so it is recorded. Candidate 3 with k=0 leaves rem 3, and 6 and 7 cannot fill it.
- Take k=1, path [2], rem 5. Candidate 3 with k=1 leaves rem 2, and 3 with k=0 leaves rem 5. Neither can be finished by 6 or 7.
- Take k=0, path [], rem 7. Candidate 3 can reach rem 1 or 4, which fail. Candidate 6 leaves rem 1, which fails. Candidate 7 with k=1 gives rem 0, so [7] is recorded.
Result: [[2,2,3],[7]].
Complexity
| Time | O(product over i of (T / candidates[i] + 1)) upper bound |
|---|---|
| Space | O(n + T / m) excluding the output |
Let n be the number of candidates, T the target and m the smallest candidate. Each candidate has at most T / candidates[i] + 1 count choices, and the tree multiplies those choices, so the product bounds the leaf count. Sum pruning keeps the real count far lower. Recursion depth is n and the path holds at most T / m numbers, which gives the space bound.
PythonTested in our runner
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
path = []
n = len(candidates)
def choose(i: int, rem: int) -> None:
if rem == 0:
result.append(path[:])
return
if i == n:
return
c = candidates[i]
for k in range(rem // c, -1, -1):
path.extend([c] * k)
choose(i + 1, rem - k * c)
del path[len(path) - k:]
choose(0, target)
return result
JavaTested in our runner
import java.util.*;
class Solution {
private List<int[]> result;
private List<Integer> path;
private int[] cand;
public int[][] combinationSum(int[] candidates, int target) {
result = new ArrayList<>();
path = new ArrayList<>();
cand = candidates;
choose(0, target);
return result.toArray(new int[0][]);
}
private void choose(int i, int rem) {
if (rem == 0) {
result.add(path.stream().mapToInt(Integer::intValue).toArray());
return;
}
if (i == cand.length) return;
int c = cand[i];
for (int k = rem / c; k >= 0; k--) {
for (int j = 0; j < k; j++) path.add(c);
choose(i + 1, rem - k * c);
for (int j = 0; j < k; j++) path.remove(path.size() - 1);
}
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> path;
choose(candidates, 0, target, path, result);
return result;
}
private:
void choose(const vector<int>& cand, int i, int rem, vector<int>& path,
vector<vector<int>>& result) {
if (rem == 0) {
result.push_back(path);
return;
}
if (i == (int)cand.size()) return;
int c = cand[i];
for (int k = rem / c; k >= 0; --k) {
for (int j = 0; j < k; ++j) path.push_back(c);
choose(cand, i + 1, rem - k * c, path, result);
for (int j = 0; j < k; ++j) path.pop_back();
}
}
};
JavaScriptTested in our runner
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const result = [];
const path = [];
const choose = (i, rem) => {
if (rem === 0) {
result.push([...path]);
return;
}
if (i === candidates.length) return;
const c = candidates[i];
for (let k = Math.floor(rem / c); k >= 0; k--) {
for (let j = 0; j < k; j++) path.push(c);
choose(i + 1, rem - k * c);
for (let j = 0; j < k; j++) path.pop();
}
};
choose(0, target);
return result;
};
GoTested in our runner
func combinationSum(candidates []int, target int) [][]int {
result := [][]int{}
path := []int{}
var choose func(i, rem int)
choose = func(i, rem int) {
if rem == 0 {
result = append(result, append([]int{}, path...))
return
}
if i == len(candidates) {
return
}
c := candidates[i]
for k := rem / c; k >= 0; k-- {
for j := 0; j < k; j++ {
path = append(path, c)
}
choose(i+1, rem-k*c)
path = path[:len(path)-k]
}
}
choose(0, target)
return result
}
C#Tested in our runner
public class Solution {
private List<int[]> result;
private List<int> path;
private int[] cand;
public int[][] combinationSum(int[] candidates, int target) {
result = new List<int[]>();
path = new List<int>();
cand = candidates;
Choose(0, target);
return result.ToArray();
}
private void Choose(int i, int rem) {
if (rem == 0) {
result.Add(path.ToArray());
return;
}
if (i == cand.Length) return;
int c = cand[i];
for (int k = rem / c; k >= 0; k--) {
for (int j = 0; j < k; j++) path.Add(c);
Choose(i + 1, rem - k * c);
path.RemoveRange(path.Count - k, k);
}
}
}
Approach 2: Backtracking with a start index
What's slow in the count-choice search: it descends one level per candidate, even for candidates that cannot fit. A branch with rem 1 still walks through 6, 7 and the end of the array before failing. Most of the tree is chains of count-zero choices that add nothing.
The insight that fixes it is to recurse on the combination itself. Loop over candidates from start, append one, and recurse with the same index i so it can be reused. Depth now equals the number of numbers in the combination, not the number of candidates, and each node does real work: it adds one number.
Steps
- Define
backtrack(start, rem)with a sharedpathlist. - If
rem == 0, record a copy ofpathand return. - Loop
ifromstartto the last index. - If
candidates[i] > rem, skip it withcontinue. - Append
candidates[i]topathand callbacktrack(i, rem - candidates[i]). Passingiallows reuse and forbids going left. - Pop the last number to undo the choice.
- Call
backtrack(0, target)and return the result.
Dry run
Candidates [2, 3, 6, 7], target 7, unsorted order is the same as sorted here.
- Root, rem 7: take 2, path [2], rem 5. Take 2 again, path [2,2], rem 3. Take 2 again, path [2,2,2], rem 1. Every candidate is larger than 1, so the loop skips all four and returns.
- Back at [2,2], rem 3: take 3, path [2,2,3], rem 0, recorded. Candidates 6 and 7 are skipped.
- Back at [2], rem 5: take 3, path [2,3], rem 2. Everything is too big. 6 and 7 are skipped too.
- Root: take 3, path [3], rem 4, then [3,3] rem 1 with nothing fitting. 6 and 7 are skipped at rem 4.
- Root: 6 gives rem 1 with nothing fitting. 7 gives rem 0, so [7] is recorded.
Result: [[2,2,3],[7]]. The loop still tests each too-large candidate once per node.
Complexity
| Time | O(n^(T / m)) upper bound |
|---|---|
| Space | O(T / m) excluding the output |
Let n be the number of candidates, T the target and m the smallest candidate. Every number added is at least m, so the recursion depth is at most T / m, and each node loops over at most n candidates. That gives at most n^(T / m) nodes as a loose bound, and each recorded answer costs O(T / m) to copy. The stack and the path both hold at most T / m entries.
PythonTested in our runner
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
result = []
path = []
def backtrack(start: int, rem: int) -> None:
if rem == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > rem:
continue
path.append(c)
backtrack(i, rem - c) # i, not i + 1: reuse is allowed
path.pop()
backtrack(0, target)
return result
JavaTested in our runner
import java.util.*;
class Solution {
private List<int[]> result;
private List<Integer> path;
private int[] cand;
public int[][] combinationSum(int[] candidates, int target) {
result = new ArrayList<>();
path = new ArrayList<>();
cand = candidates;
backtrack(0, target);
return result.toArray(new int[0][]);
}
private void backtrack(int start, int rem) {
if (rem == 0) {
result.add(path.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = start; i < cand.length; i++) {
int c = cand[i];
if (c > rem) continue;
path.add(c);
backtrack(i, rem - c);
path.remove(path.size() - 1);
}
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> result;
vector<int> path;
backtrack(candidates, 0, target, path, result);
return result;
}
private:
void backtrack(const vector<int>& cand, int start, int rem, vector<int>& path,
vector<vector<int>>& result) {
if (rem == 0) {
result.push_back(path);
return;
}
for (int i = start; i < (int)cand.size(); ++i) {
if (cand[i] > rem) continue;
path.push_back(cand[i]);
backtrack(cand, i, rem - cand[i], path, result);
path.pop_back();
}
}
};
JavaScriptTested in our runner
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const result = [];
const path = [];
const backtrack = (start, rem) => {
if (rem === 0) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
const c = candidates[i];
if (c > rem) continue;
path.push(c);
backtrack(i, rem - c);
path.pop();
}
};
backtrack(0, target);
return result;
};
GoTested in our runner
func combinationSum(candidates []int, target int) [][]int {
result := [][]int{}
path := []int{}
var backtrack func(start, rem int)
backtrack = func(start, rem int) {
if rem == 0 {
result = append(result, append([]int{}, path...))
return
}
for i := start; i < len(candidates); i++ {
c := candidates[i]
if c > rem {
continue
}
path = append(path, c)
backtrack(i, rem-c)
path = path[:len(path)-1]
}
}
backtrack(0, target)
return result
}
C#Tested in our runner
public class Solution {
private List<int[]> result;
private List<int> path;
private int[] cand;
public int[][] combinationSum(int[] candidates, int target) {
result = new List<int[]>();
path = new List<int>();
cand = candidates;
Backtrack(0, target);
return result.ToArray();
}
private void Backtrack(int start, int rem) {
if (rem == 0) {
result.Add(path.ToArray());
return;
}
for (int i = start; i < cand.Length; i++) {
int c = cand[i];
if (c > rem) continue;
path.Add(c);
Backtrack(i, rem - c);
path.RemoveAt(path.Count - 1);
}
}
}

Solution pattern
Combination Sum
Part of Backtracking Patterns
Approach 3: Sort, then backtrack with early breakOptimalCombination Sum
What's slow in the start-index version: at every node the loop still looks at each candidate to its right, including the ones that are too large. If the candidates are in arbitrary order, you must test every one with continue.
The insight that fixes it is to sort candidates ascending first. Once candidates[i] > rem, every later candidate is at least as large, so none can fit. Replace continue with break and the loop ends at the first failure.
Sorting costs O(n log n) once and saves scanning work at every node. Answers also come out in a predictable order.
Steps
- Sort a copy of
candidatesin ascending order. - Define
backtrack(start, rem)with a sharedpathlist. - If
rem == 0, record a copy ofpathand return. - Loop
ifromstartto the end of the sorted array. - If
nums[i] > rem,break. Every later value is larger, so nothing else fits. - Append
nums[i], recurse withbacktrack(i, rem - nums[i]), then pop. - Call
backtrack(0, target)and return the result.
Dry run
The table traces sorted candidates [2, 3, 6, 7] with target 7. rem is the sum still needed when the call starts.
| Step | path | rem | Action |
|---|---|---|---|
| 1 | [] | 7 | i=0, take 2 |
| 2 | [2] | 5 | i=0, take 2 |
| 3 | [2,2] | 3 | i=0, take 2 |
| 4 | [2,2,2] | 1 | 2 > 1, break, return |
| 5 | [2,2] | 3 | i=1, take 3 |
| 6 | [2,2,3] | 0 | record [2,2,3], return |
| 7 | [2,2] | 3 | i=2, 6 > 3, break, return |
| 8 | [2] | 5 | i=1, take 3, path [2,3], rem 2 |
| 9 | [2,3] | 2 | 3 > 2, break, return |
| 10 | [2] | 5 | i=2, 6 > 5, break, return |
| 11 | [] | 7 | i=1, take 3, path [3], rem 4 |
| 12 | [3] | 4 | i=1, take 3, path [3,3], rem 1; then 3 > 1, break |
| 13 | [3] | 4 | i=2, 6 > 4, break, return |
| 14 | [] | 7 | i=2, take 6, path [6], rem 1; then 6 > 1, break |
| 15 | [] | 7 | i=3, take 7, path [7], rem 0, record [7] |
The recorded answers are [2,2,3] and [7], so the output is [[2,2,3],[7]]. Step 4 ends the loop after one comparison instead of four.
Complexity
| Time | O(n^(T / m)) upper bound |
|---|---|
| Space | O(T / m) excluding the output |
Let n be the number of candidates, T the target and m the smallest candidate. Sorting costs O(n log n), which is tiny next to the search. Depth is at most T / m because every pick is at least m, and each node loops over at most n values, so n^(T / m) bounds the node count.
The break only shrinks the loop at each node, so the bound stays the same but the work in practice drops. Space is the recursion stack plus the path, both at most T / m.
PythonTested in our runner
from typing import List
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
nums = sorted(candidates)
result = []
path = []
def backtrack(start: int, rem: int) -> None:
if rem == 0:
result.append(path[:])
return
for i in range(start, len(nums)):
if nums[i] > rem:
break # sorted, so every later value is too big as well
path.append(nums[i])
backtrack(i, rem - nums[i])
path.pop()
backtrack(0, target)
return result
JavaTested in our runner
import java.util.*;
class Solution {
private List<int[]> result;
private List<Integer> path;
private int[] nums;
public int[][] combinationSum(int[] candidates, int target) {
nums = candidates.clone();
Arrays.sort(nums);
result = new ArrayList<>();
path = new ArrayList<>();
backtrack(0, target);
return result.toArray(new int[0][]);
}
private void backtrack(int start, int rem) {
if (rem == 0) {
result.add(path.stream().mapToInt(Integer::intValue).toArray());
return;
}
for (int i = start; i < nums.length; i++) {
if (nums[i] > rem) break;
path.add(nums[i]);
backtrack(i, rem - nums[i]);
path.remove(path.size() - 1);
}
}
}
C++Tested in our runner
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> nums = candidates;
sort(nums.begin(), nums.end());
vector<vector<int>> result;
vector<int> path;
backtrack(nums, 0, target, path, result);
return result;
}
private:
void backtrack(const vector<int>& nums, int start, int rem, vector<int>& path,
vector<vector<int>>& result) {
if (rem == 0) {
result.push_back(path);
return;
}
for (int i = start; i < (int)nums.size(); ++i) {
if (nums[i] > rem) break;
path.push_back(nums[i]);
backtrack(nums, i, rem - nums[i], path, result);
path.pop_back();
}
}
};
JavaScriptTested in our runner
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const nums = [...candidates].sort((a, b) => a - b);
const result = [];
const path = [];
const backtrack = (start, rem) => {
if (rem === 0) {
result.push([...path]);
return;
}
for (let i = start; i < nums.length; i++) {
if (nums[i] > rem) break;
path.push(nums[i]);
backtrack(i, rem - nums[i]);
path.pop();
}
};
backtrack(0, target);
return result;
};
GoTested in our runner
import "sort"
func combinationSum(candidates []int, target int) [][]int {
nums := append([]int{}, candidates...)
sort.Ints(nums)
result := [][]int{}
path := []int{}
var backtrack func(start, rem int)
backtrack = func(start, rem int) {
if rem == 0 {
result = append(result, append([]int{}, path...))
return
}
for i := start; i < len(nums); i++ {
if nums[i] > rem {
break
}
path = append(path, nums[i])
backtrack(i, rem-nums[i])
path = path[:len(path)-1]
}
}
backtrack(0, target)
return result
}
C#Tested in our runner
public class Solution {
private List<int[]> result;
private List<int> path;
private int[] nums;
public int[][] combinationSum(int[] candidates, int target) {
nums = (int[])candidates.Clone();
Array.Sort(nums);
result = new List<int[]>();
path = new List<int>();
Backtrack(0, target);
return result.ToArray();
}
private void Backtrack(int start, int rem) {
if (rem == 0) {
result.Add(path.ToArray());
return;
}
for (int i = start; i < nums.Length; i++) {
if (nums[i] > rem) break;
path.Add(nums[i]);
Backtrack(i, rem - nums[i]);
path.RemoveAt(path.Count - 1);
}
}
}
Common mistakes
- Calling
backtrack(0, rem - c)inside the loop. Every level restarts from the first candidate, so [2,3] and [3,2] both appear. Passiso the search never moves left. - Calling
backtrack(i + 1, rem - c). That forbids reuse, so [2,2,3] is never found. Passi, noti + 1, to let the same number repeat. - Storing
result.append(path)orresult.add(path)without a copy. The path keeps changing, so every stored answer ends up empty. Storepath[:],new ArrayList<>(path)or a fresh array. - Using
breakon an unsorted array. A large value early in the list would stop the loop before smaller values to its right are tried, and valid answers vanish. Sort first, or usecontinueinstead. - Forgetting to undo the choice after the recursive call, such as a missing
path.pop(). The next sibling then sees leftover numbers and builds wrong combinations. Every push needs a matching pop. - In Java and C#, returning a
List<List<Integer>>when the signature isint[][]. Convert each recorded path to anint[]and the outer list to an array.
Edge cases
candidates = [2], target = 1: no combination exists, so return an empty list.candidates = [7], target = 7: one candidate equals the target, so return [[7]].candidates = [2], target = 40: the only answer is twenty 2s. Recursion depth reaches 20, which is fine.candidates = [3, 2, 7, 6]in unsorted order: the answer set is the same as for [2, 3, 6, 7]. Only the order of the answers may differ.- Target smaller than every candidate, such as
[5, 6], target 4: the loop skips or breaks immediately and the result is empty. - 30 distinct candidates with
target = 40: depth is small and pruning keeps the search fast, but the result list must still hold fewer than 150 combinations.
Follow-ups interviewers ask
- What changes if candidates may contain duplicates and each element can be used only once (Combination Sum II)?
- Sort the array, recurse with
i + 1so each element is used once, and skip a value when it equals the previous value at the same loop level. The skip stops two equal siblings from starting the same subtree and producing duplicate answers. - What if you only need the number of combinations, not the combinations themselves?
- Use dynamic programming. Keep
ways[s]as the count of multisets summing tos, setways[0] = 1, and for each candidate in the outer loop updateways[s] += ways[s - c]forsfromcto the target. That runs in O(n * T) time and O(T) space. Putting candidates in the outer loop counts each multiset once instead of counting orderings. - What if candidates could be zero or negative?
- The search no longer terminates, because the running sum can stay at or below the target forever. A zero adds infinitely many answers by repeating it. You would need an explicit cap on combination length, and the early
breakonnums[i] > remis no longer valid.
Combination Sum FAQ
What is the time complexity of Combination Sum?
It is O(n^(T / m)) as an upper bound, where n is the number of candidates, T the target and m the smallest candidate. The tree has depth at most T / m and each node branches at most n ways. Pruning and the guarantee of fewer than 150 answers make real runs much cheaper than this bound. Space is O(T / m) beyond the output.
Why use backtracking for Combination Sum?
You must list every valid combination, not count them, so you have to build each one explicitly. Backtracking builds one candidate answer at a time, checks it, and undoes the last pick to try another. Because all numbers are positive, you can cut a branch as soon as the sum exceeds the target.
How do I solve the Combination Sum problem on LeetCode?
Sort the candidates, then run a recursive function with a start index and the remaining sum. Add a number, recurse with the same index so it can repeat, and pop it afterwards. Record the path when the remaining sum hits zero, and break when the next candidate is larger than what remains.
What is combination sum?
It is the task of finding all multisets drawn from a list of numbers that add up to a given target. In LeetCode 39 each number can be reused any number of times, and two combinations are the same if they use each number equally often. Order inside a combination does not matter.
Can Combination Sum be solved in O(1) extra space?
No. You need a path that holds up to T / m numbers and a recursion stack of the same depth, where T is the target and m the smallest candidate. An iterative version replaces the stack with an explicit one but still stores the path. The output list is not counted as extra space.
Why does my Python solution return a list of empty lists?
You appended the shared path object, not a copy. Backtracking pops from it until it is empty, and every stored reference shows that final state. Use result.append(path[:]) or list(path).
What is the difference between Combination Sum and Combination Sum II?
In Combination Sum numbers are distinct and reusable, so you recurse with i. In Combination Sum II the list may hold duplicates and each element is used once, so you sort, recurse with i + 1, and skip equal neighbours at the same depth.
Asked at
See which companies ask this — Pro
Related problems
- Combination Sum II · same technique: Combination Sum
- Partition to K Equal Sum Subsets · same technique: Combination Sum
- N-Queens · next harder, same pattern
- Word Search · same pattern: Backtracking Patterns
- Subsets · same pattern: Backtracking Patterns
- Permutations · same pattern: Backtracking Patterns
- Letter Combinations of a Phone Number · same pattern: Backtracking Patterns
- Generate Parentheses · same pattern: Backtracking Patterns
- Palindrome Partitioning · same pattern: Backtracking Patterns
- Subsets II · same pattern: Backtracking Patterns