[leetcode]Combination Sum II

来源:互联网 发布:达内大数据课程怎么样 编辑:程序博客网 时间:2024/06/04 07:21
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;    }};
0 0
原创粉丝点击