40. Combination Sum II
Description
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Analysis
这道题与39.Combination Sum的区别在于,此题中元素只能使用一次,所以唯一需要改动的地方就是每次递归调用的深度需要+1,代码如下:
code
class Solution {
void backtracking(vector<vector<int>> & res,vector<int> & temp,vector<int> & candidates,int remain,int start){
if(remain<0) return;
if(remain==0){
res.push_back(temp);
return;
}
for(int i=start;i<candidates.size();++i){
if(i>start&&candidates[i]==candidates[i-1]) continue;
temp.push_back(candidates[i]);
backtracking(res,temp,candidates,remain-candidates[i],i+1);
temp.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<int> temp;
vector<vector<int>> res;
sort(candidates.begin(),candidates.end());
backtracking(res,temp,candidates,target,0);
return res;
}
};