LeetCode 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 (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> > result;
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        sort(candidates.begin(), candidates.end());
        vector<int> tempRes;
        dfs(candidates, tempRes, target, 0);
        return result;
    }
    void dfs(vector<int> &candidates, vector<int> &tempRes, int target, int start) {
        for(int i = start; i < candidates.size(); ++i) {
            if(candidates[i] == target) {
                tempRes.push_back(candidates[i]);
                result.push_back(tempRes);
                tempRes.pop_back();
                return ;
            }
            if(candidates[i] < target) {
                tempRes.push_back(candidates[i]);
                dfs(candidates, tempRes, target - candidates[i], i);
                tempRes.pop_back();
            }
        }
        return;
    }
};

你可能感兴趣的:(array,DFS,backtracking,recursion)