思路详解见:https://blog.csdn.net/qq_40467670/article/details/120577321
此题是在这一题的基础上多了去重的操作。
题目链接:https://leetcode-cn.com/problems/combination-sum-ii/
题目如下:
class Solution {
public:
vector<vector<int>> ans;
vector<int> cur;
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
dfs(candidates,target,0);
return ans;
}
void dfs(vector<int>& candidates,int target,int start){
if(target==0){
ans.push_back(cur);
return ;
}
for(int i=start;i<candidates.size();++i){
if(i>start&&candidates[i]==candidates[i-1]) continue;//important,去重固定套路,不是[i]==[i+1]
if(candidates[i]>target) break;
cur.push_back(candidates[i]);
dfs(candidates,target-candidates[i],i+1);
cur.pop_back();
}
}
};