这题个人感觉很难,一开始按照正常的组合写法没有考虑到去重问题,根据以往写三四数之和的经验,对数组进行了排序,再进行去重逻辑的编写才得以通关,详细去重可以去看看代码随想录,甚至有使用到used数组讲解树枝和数层的去重
class Solution {
private:
vector<vector<int>> result;
vector<int> combination;
void combinationSum2(vector<int>& candidates,int target,int count,int startIndex){
if(count==target)
result.push_back(combination);
else{
for(int i=startIndex;i<candidates.size()&&count<target;i++){
//去重
if(i>startIndex&&candidates[i]==candidates[i-1])
continue;
combination.push_back(candidates[i]);
combinationSum2(candidates,target,count+candidates[i],i+1);
combination.pop_back();
}
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
combinationSum2(candidates,target,0,0);
return result;
}
};
标签:target,组合,int,combination,vector,candidates,leecode40,combinationSum2,总和
From: https://blog.csdn.net/weixin_74175349/article/details/143604831