Combination Sum II
Medium
Topics
Given candidates (which may contain duplicates) and a target, return all unique combinations summing to target. Each candidate may be used at most once.
Example 1
Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [[1,1,6],[1,2,5],[1,7],[2,6]]
Example 2
Input: candidates = [2,5,2,1,2], target = 5 Output: [[1,2,2],[5]]
Constraints
- 1 <= candidates.length <= 100
- 1 <= candidates[i] <= 50
- 1 <= target <= 30
Editorial — intuition, approach, complexity and pitfalls
Intuition
Like Combination Sum, but each item is used once and duplicates must not produce duplicate combinations. Sort, advance the index each pick, and skip equal values at the same depth.
Approach
- Sort candidates.
- DFS advancing to i+1 (each used once).
- Skip
candidates[i] == candidates[i-1]when i > start to dedupe.
Dry Run
candidates [10,1,2,7,6,1,5] sorted to [1, 1, 2, 5, 6, 7, 10], target 8
answer [1,1,6] | [1,2,5] | [1,7] | [2,6]
This page needs both controls at once, and each one alone is wrong in its own way.
`dfs(i + 1, ...)` enforces single use. Recurse from `i` instead and the same
element is reusable, which is combination-sum's rule, not this one -- the output
balloons to ten results including [1,1,1,1,1,1,1,1] and [2,2,2,2].
`i > start` suppresses duplicate branches. Drop the skip entirely and the two 1s
each start their own branch at the top level, producing [1,2,5] and [1,7] twice:
six results instead of four, with two exact duplicates.
Change it to `i > 0` and it over-suppresses, exactly as in subsets-ii: [1,1,6]
vanishes, leaving only [1,2,5] [1,7] [2,6]. The combination that legitimately
USES both 1s is the casualty.
So: i + 1 controls how often one element may be used, and i > start controls how
often one VALUE may begin a branch. They are independent, and getting one right
does not cover the other.Complexity
- Time — O(2^n): subset exploration with pruning.
- Space — O(n): recursion depth.
Common Pitfalls
- Advance to i+1 (single use) and skip duplicates only at i > start.
Full Solution — all languages
class Solution:
def combinationSum2(self, candidates, target):
candidates.sort()
res=[]
def dfs(start,rem,path):
if rem==0: res.append(path[:]); return
for i in range(start,len(candidates)):
if i>start and candidates[i]==candidates[i-1]: continue
if candidates[i]>rem: break
path.append(candidates[i]); dfs(i+1,rem-candidates[i],path); path.pop()
dfs(0,target,[])
return resimport java.util.*;
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> res=new ArrayList<>();
dfs(candidates,0,target,new ArrayList<>(),res);
return res;
}
void dfs(int[] c,int start,int rem,List<Integer> path,List<List<Integer>> res) {
if(rem==0) {
res.add(new ArrayList<>(path));
return;
}
for(int i=start;i<c.length;i++) {
if(i>start&&c[i]==c[i-1])continue;
if(c[i]>rem)break;
path.add(c[i]);
dfs(c,i+1,rem-c[i],path,res);
path.remove(path.size()-1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> path;
function<void(int,int)> dfs=[&](int start,int rem) {
if(rem==0) {
res.push_back(path);
return;
}
for(int i=start;i<(int)candidates.size();i++) {
if(i>start&&candidates[i]==candidates[i-1])continue;
if(candidates[i]>rem)break;
path.push_back(candidates[i]);
dfs(i+1,rem-candidates[i]);
path.pop_back();
}
};
dfs(0,target);
return res;
}
};/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/ var combinationSum2 = function(candidates, target) {
candidates.sort((a,b)=>a-b);
const res=[];
function dfs(start,rem,path) {
if(rem===0) {
res.push(path.slice());
return;
}
for(let i=start;i<candidates.length;i++) {
if(i>start&&candidates[i]===candidates[i-1])continue;
if(candidates[i]>rem)break;
path.push(candidates[i]);
dfs(i+1,rem-candidates[i],path);
path.pop();
}
}
dfs(0,target,[]);
return res;
};
Asked at
Snap