class Solution {
public:
void help(vector<int> &v,int now,int sum,int target,vector<int> &path,vector<vector<int> > &ans){
//now表示当前的数
//sum表示当前所选择的数的和
if(sum>target){//
return;
}
if(now>=v.size()){
if(sum==target){//组合成功
ans.push_back(path);
}
return;
}
if((now==0)||(v[now-1]!=v[now])){
path.push_back(v[now]);
help(v,now,sum+v[now],target,path,ans);
path.pop_back();//恢复path
}
help(v,now+1,sum,target,path,ans);//不选择当前的数
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());//排序
vector<int> path;//存放已选择的数
vector<vector<int> > ans;
help(candidates,0,0,target,path,ans);
return ans;
}
};
[leetcode]Combination Sum
最新推荐文章于 2019-05-07 10:37:18 发布