Leetcode: 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] 

又是DFS,熟悉了之后就比较简单了。

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        
        vector<int> v;
        combinationSumUtil(candidates, v, target, 0);
        
        return result;
    }
    
    void combinationSumUtil(vector<int> &candidates, vector<int> &comb, int sum, int start) {
        if (sum == 0) {
            result.push_back(comb);
            return;
        }
        
        for (int i = start; i < candidates.size(); ++i) {
            if (candidates[i] <= sum) {
                comb.push_back(candidates[i]);
                combinationSumUtil(candidates, comb, sum - candidates[i], i);
                comb.pop_back();
            }
            else {
                break;
            }
        }
    }

private:
    vector<vector<int> > result;
};

======================第二次======================

class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        vector<vector<int>> result;
        vector<int> comb;
        sort(candidates.begin(), candidates.end());
        combine_util(result, candidates, comb, target, 0);
        
        return result;
    }
    
    void combine_util(vector<vector<int>> &result, vector<int> &candidates, vector<int> &comb, int target, int start) {
        if (target == 0) {
            result.push_back(comb);
            return;
        }
        
        for (int i = start; i < candidates.size(); ++i) {
            if (candidates[i] <= target) {
                comb.push_back(candidates[i]);
                combine_util(result, candidates, comb, target - candidates[i], i);
                comb.pop_back();
            }
            else {
                break;
            }
        }
    }
};


你可能感兴趣的:(LeetCode)