39. Combination Sum (Back-Track)

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:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());
        backTracking(candidates,0,target);
        return result;
    }
    
    void backTracking(vector<int>& candidates, int depth, int target){
        if(target==0){
            result.push_back(item);
            return;
        }
        if(target<0 || depth >= candidates.size()) return;
        
        item.push_back(candidates[depth] );
        backTracking(candidates,depth, target-candidates[depth]);
        item.pop_back();
        backTracking(candidates,depth+1, target);
    }
private:
    vector<int> item;
    vector<vector<int>> result;
};

 

posted on 2015-10-05 08:26  joannae  阅读(191)  评论(0编辑  收藏  举报

导航