leetCode 组合数II 40
这道题和以往不同的是要去重
//关键
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
//如果used上一个used为true表示包含在其中,可以取,如果false,肯会重复,如下图
class Solution {
private:
vector<vector<int>> result;
vector<int> ans;
public:
int sum = 0;
void backtracking(vector<int>& candidates, int target, int startIndex,vector<bool> used){
if (sum > target) {
return;
} else if (sum == target) {
result.push_back(ans);
return;
}
for (int i = startIndex; i < candidates.size(); i++) {
if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
continue;
}
sum += candidates[i];
ans.push_back(candidates[i]);
used[i] = true;
backtracking(candidates, target, i + 1, used);
used[i] = false;
sum -= candidates[i];
ans.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<bool> used(candidates.size(), false);
backtracking(candidates, target, 0, used);
return result;
}
};
标签:used,false,target,组合,int,II,vector,candidates
From: https://www.cnblogs.com/tsqo/p/17178072.html