[leetcode][回溯] Combination Sum

来源:互联网 发布:热力计算软件 编辑:程序博客网 时间:2024/04/30 15:26

题目:

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]


class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int> > res;        sort(candidates.begin(), candidates.end());        vector<int> oneCombination;        combinationSumCore(candidates, 0, target, oneCombination, res);        return res;    }private:    void combinationSumCore(vector<int>& candidates, int start, int target, vector<int> oneCombination, vector<vector<int> > &res){        for(int i = start; i < candidates.size(); ++i){            oneCombination.push_back(candidates[i]);//当前值大于target,则它后面的值也肯定大于target,不可能组成target            if(candidates[i] >= target){                if(candidates[i] == target) res.push_back(oneCombination);                break;            }            combinationSumCore(candidates, i, target-candidates[i], oneCombination, res);            oneCombination.pop_back();        }    }};




0 0