Combination Sum

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

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

除了拼写错误,竟然一次过了……没有查有没有更优的算法。

class Solution {
public:
    vector<vector<int> > re;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {

        sort(candidates.begin(),candidates.end());
        vector<int> tempresult;
        com(candidates,target,tempresult,0,-1);
        return re;
        
    }
    void com(vector<int> &candidates,int target,vector<int> now,int min,int push)
    {
        if(push>=0)
        {
            now.push_back(candidates[push]);
            target -= candidates[push];
        }
        //if(candidates == NULL)return;
        if(target == 0)
        {
            re.push_back(now);
            return;
        }
        if(target < candidates[min]) return;
        
        for(int i = min ; i < candidates.size(); i++)
        {
            com(candidates,target,now,i,i);
        }
    }
};

  

原文地址:https://www.cnblogs.com/pengyu2003/p/3594725.html