您的位置:首页 > 其它

[leetcode]Combination Sum II

2015-10-12 17:24 405 查看
class Solution {
public:
void help(vector<int> &v,int now,int sum,int target,vector<int> &path,vector<vector<int> >&ans,bool last){
//now表示当前的数
//sum表示当前所选的数的和
//target表示目标数据
//path表示所有已选的数
//last上一个数是否选择
//相同的数连续取,不能跳着取
if(sum>target){
return;
}
if(now>=v.size()){
if(sum==target){//组合完成
ans.push_back(path);
}
return;
}
if((now==0)||(v[now-1]!=v[now])||last){//第一个必须取;当前数和前一个数不一样;当前数和前一个一样,并且取了前一个数
path.push_back(v[now]);
help(v,now+1,sum+v[now],target,path,ans,true);
path.pop_back();//回复path
}
help(v,now+1,sum,target,path,ans,false);//不取当前数
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());//排序
vector<int> path;//已选的数
vector<vector<int> > ans;//结果
help(candidates,0,0,target,path,ans,true);
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: