C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
C may only be used once
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
[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 {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
vector<int> temp;
vector<vector<int>> result;
myComb2(candidates,target,0,temp,result);
return result;
}
void myComb2(vector<int>& candidates, int target,int index,vector<int> & temp,vector<vector<int>> & result){
//
if(target < 0) return;
if(target == 0){
// temp.push_back(candidates[index]);
result.push_back(temp);
return;
}
for(int i = index; i < candidates.size() && target >= candidates[i]; i ++){
if((i == index) || (candidates[i] != candidates[i - 1])){
temp.push_back(candidates[i]);
myComb2(candidates,target - candidates[i],i + 1,temp,result);
temp.pop_back();
}
}
}
};