39. Combination Sum(C++)

Given a set of candidate numbers (C) (without duplicates) 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.
  • 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]
]

Solution: 回溯法
class Solution {
public:
    
    void combination(vector<int>& candidates, int target,vector<int>& tmp,vector<vector<int>>& myvec,int start){
        if(!target){
            myvec.push_back(tmp);
            return;
        }
        for(int i=start;i<candidates.size()&&candidates[i]<=target;i++){
            tmp.push_back(candidates[i]);
            combination(candidates,target-candidates[i],tmp,myvec,i);
            tmp.pop_back();
        }
        
    }

    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> myvec;
        sort(candidates.begin(),candidates.end());
        vector<int> tmp;
        combination(candidates,target,tmp,myvec,0);
        return myvec;
    }
};

  

posted @ 2017-04-13 21:00  DevinGu  阅读(190)  评论(0编辑  收藏  举报