文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
class Solution {
public:
vector> combinationSum2(vector& candidates, int target) {
set> s;
sort(candidates.begin(), candidates.end());
vector combination;
combinationSum2(s, candidates, combination, target, 0, 0);
return vector>(s.begin(), s.end());
}
private:
void combinationSum2(set>& result, vector& candidates, vector& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.insert(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};
class Solution {
public:
vector> combinationSum2(vector& candidates, int target) {
set> s;
sort(candidates.begin(), candidates.end());
vector combination;
combinationSum2(s, candidates, combination, target, 0, 0);
return vector>(s.begin(), s.end());
}
private:
void combinationSum2(set>& result, vector& candidates, vector& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.insert(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
if(sum + candidates[i] > target) {
break;
}
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};
class Solution {
public:
vector> combinationSum2(vector& candidates, int target) {
vector> result;
sort(candidates.begin(), candidates.end());
vector combination;
combinationSum2(result, candidates, combination, target, 0, 0);
return result;
}
private:
void combinationSum2(vector>& result, vector& candidates, vector& combination, int& target, int sum, int begin) {
if(sum > target) {
return;
}
if(sum == target) {
result.push_back(combination);
return;
}
for(int i = begin; i < candidates.size(); i++) {
if(sum + candidates[i] > target) {
break;
}
if(i > begin && candidates[i] == candidates[i - 1]) {
continue;
}
combination.push_back(candidates[i]);
combinationSum2(result, candidates, combination, target, sum + candidates[i], i + 1);
combination.pop_back();
}
}
};