标签:
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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
class Solution { public: void getCombinationSum(int currentSum,vector<int>& candidates, int index,vector <vector<int>> &solution, vector <int> &result, int target){ if(currentSum == target){ //如果和等于目标,则把该结果压入solution,返回上一 层 solution.push_back(result); return; } else{ //如果和小于目标,则可以继续加入值 for(int i = index; i < candidates.size() ;i++){ currentSum += candidates[i]; if(currentSum> target){//加值后大于目标,则该队列不可能再复合要求,直接break该循环 currentSum -= candidates[i]; break; } result.push_back(candidates[i]);//把当前结果压入,继续递归调用 getCombinationSum(currentSum,candidates,i,solution,result,target); currentSum -= candidates[i];//返回的情况说明之前找到了一个解,所以把最后压入的去掉,然后继续循环添加新值 result.pop_back(); } } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector <vector<int>> solution; vector <int> result; int currentSum = 0; sort(candidates.begin(),candidates.end());//先把输入排序,确保输出是有序的 getCombinationSum(currentSum,candidates,0,solution,result,target); return solution; } };
标签:
原文地址:http://www.cnblogs.com/yang-xiong/p/5215443.html