Combination Sum

来源:互联网 发布:软考程序员科目有哪些 编辑:程序博客网 时间:2024/06/05 20:37

iven 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] 

典型的backtracking. 每一个solution都先向下加入一个解,然后在下一次递归中测试,如果测试通过,自然就会被push到result中,如果不通过,继续活着返回,尝试第二个解。 需要注意的是因为有重复出现元素,所以在递归中的循环需要考虑当前元素。。。不管符合不符合,solution都要被pop,因为需要尝试其他可能。

class Solution {public:    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {       vector<int> solution;       vector< vector<int> > res;       int sum=0;       sort(candidates.begin(),candidates.end());       helper(candidates,solution,res,sum,0,target);       return res;    }        void helper(vector<int>& candidates, vector<int>& solution, vector< vector<int> > & res,         int& sum, int level, int target)        {            if (sum>target)                return;            if (sum==target){                res.push_back(solution);                return;            }            for (int i=level; i<candidates.size();i++){                sum+=candidates[i];                solution.push_back(candidates[i]);                helper(candidates,solution,res,sum,i,target);                solution.pop_back();                sum-=candidates[i];            }        }};



0 0
原创粉丝点击