40. Combination Sum II

来源:互联网 发布:南京网络品牌推广 编辑:程序博客网 时间:2024/06/04 00:51

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is: 

[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]

Subscribe to see which companies asked this question.

没有消除重复情况的代码:

class Solution {public:    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {        vector<int> temp;        vector<vector<int>> ret;        help(candidates,0,temp,target,ret);        return ret;    }private:    void help(vector<int>& candidates,int index,vector<int> temp,int target, vector<vector<int>>& ret)    {        if(target==0&&index<=candidates.size())        {            ret.push_back(temp);            return;        }        for(int i=index;i<candidates.size();i++)        {            temp.push_back(candidates[i]);            help(candidates,i+1,temp, target-candidates[i],ret);            temp.pop_back();        }    }};

大神的代码;

好吧,看到一个sort。我表示很无奈。并不像说什么。我说我怎么半天看不懂这句代码

if(i&&num[i]==num[i-1]&&i>order) continue; // check duplicate combination

class Solution {public:    vector<vector<int> > combinationSum2(vector<int> &num, int target)     {        vector<vector<int>> res;        sort(num.begin(),num.end());        vector<int> local;        findCombination(res, 0, target, local, num);        return res;    }    void findCombination(vector<vector<int>>& res, const int order, const int target, vector<int>& local, const vector<int>& num)    {        if(target==0)        {            res.push_back(local);            return;        }        else        {            for(int i = order;i<num.size();i++) // iterative component            {                if(num[i]>target) return;                if(i&&num[i]==num[i-1]&&i>order) continue; // check duplicate combination                local.push_back(num[i]),                findCombination(res,i+1,target-num[i],local,num); // recursive componenet                local.pop_back();            }        }    }};




原创粉丝点击