标签:des style blog http color os io 使用 ar
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:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
寻找target成员的过程中,如果candidates[i]是组成target的成员之一,那么寻找target-candidates[i]的子问题与原题就完全一致,因此是典型的递归。
参数列表中:result设为全局变量,用于记录所有可行的路径,因此使用引用(&);curPath是每次递归栈中独立部分,因此使用拷贝复制
对candidates的排序及去重的目的就是防止结果的重复,比如7 --> 2,2,3/2,3,2/3,2,2
class Solution { public: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { vector<vector<int> > result; //排序 sort(candidates.begin(), candidates.end()); //去重 vector<int>::iterator iter = unique(candidates.begin(), candidates.end()); candidates.erase(iter, candidates.end()); vector<int> curPath; searchPath(candidates, result, curPath, 0, target); return result; } void searchPath(vector<int> &candidates, vector<vector<int> > &result, vector<int> curPath, int index, int target) { for(int i = index; i < candidates.size() && candidates[i] <= target; i ++) { if(candidates[i] < target) { curPath.push_back(candidates[i]); //此处仍为index,不能+1,同元素可以重复多次 searchPath(candidates, result, curPath, i, target-candidates[i]); curPath.pop_back(); } else// if(candidates[i] == target) {//结束 curPath.push_back(candidates[i]); result.push_back(curPath); return; } } } };
标签:des style blog http color os io 使用 ar
原文地址:http://www.cnblogs.com/ganganloveu/p/3961332.html