题目
代码(首刷部分看解析)
为了防止重复,在dfs的for循环里面需要判断是否与上一个数相同
class Solution {
public:
vector<vector<int>> res;
vector<int> ans;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
int n = candidates.size();
sort(candidates.begin(), candidates.end());
dfs(candidates, 0, target, n, 0);
return res;
}
void dfs(vector<int>& candidates, int sum, int target, int n, int k) {
if(sum == target) {
res.push_back(ans);
return;
}
if(sum > target)
return;
int pre = 0;
for(int i = k; i < n; ++i) {
if(i > k && candidates[i] == candidates[i-1]) continue;
sum += candidates[i];
ans.push_back(candidates[i]);
dfs(candidates, sum, target, n, i+1);
sum -= candidates[i];
ans.pop_back();
}
}
};
代码(10.2 二刷自解)
class Solution {
public:
vector<vector<int>> res;
vector<int> tmp;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
backtrack(candidates, target, 0);
return res;
}
void backtrack(vector<int>& candidates, int target, int k) {
if(target < 0)
return;
if(target == 0) {
res.emplace_back(tmp);
return;
}
for(int i = k; i < candidates.size(); i++) {
if(i > k && candidates[i] == candidates[i-1]) continue;
tmp.emplace_back(candidates[i]);
backtrack(candidates, target-candidates[i], i+1);
tmp.pop_back();
}
}
};