39. 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 (a1, a2, … , 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:
    void dfs(vector<int>& a,vector<vector<int>>&v,vector<int>&tmp,int id,int sum,int target){
        if(sum>target)return ;
        if(sum==target){
            v.push_back(tmp);
            return ;
        }
        for(int i=id;i<a.size();i++){
            if(a[i]+sum>target)break;//重要的剪枝
            tmp.push_back(a[i]);
            dfs(a,v,tmp,i,sum+a[i],target);
            tmp.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(),candidates.end());
        vector<vector<int>>v;
        vector<int>tmp;
        dfs(candidates,v,tmp,0,0,target);
        return v;
    }
};

 

posted on 2016-04-05 16:52  Beserious  阅读(194)  评论(0编辑  收藏  举报