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]
]
方法:递归调用即可
class Solution {
private:
void recursive(int sum,vector<vector<int>>& res,vector<int>& combination,vector<int>& candidates, int target,int now){
if(sum==target){
res.push_back(combination);
return ;
}
for(int i=now+1;i<candidates.size();++i){
if(i!=now+1&&candidates[i]==candidates[i-1])
continue;
if(sum+candidates[i]>target)
return;
combination.push_back(candidates[i]);
recursive(sum+candidates[i],res,combination,candidates,target,i);
combination.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
vector<int> combination;
sort(candidates.begin(),candidates.end());
for(int i=0;i<candidates.size();++i){
if(i!=0&&candidates[i]==candidates[i-1])
continue;
combination.push_back(candidates[i]);
recursive(candidates[i],res,combination,candidates,target,i);
combination.pop_back();
}
return res;
}
};