题目如下:
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 (a1, a2, … , 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的题目之后, 发现这道题目就是标准的DFS题目,具体分下见下面的代码。
我的代码:
class Solution { public: void combinationSumMy(vector<int> &candidates, vector<int> &every, vector<vector<int> > & final, int target, int start) { if (target == 0) { //说明已经找到了合适的结果向量,保存当前的结果向量every到2维向量final中 final.push_back(every); return; }else { for (int i = start; i < candidates.size(); ++i) { if (candidates[i] > target) return; //剪枝,因为题目说了都是正数 every.push_back(candidates[i]); //把当前candidate[i]放入结果向量中, target 变化为target - candidate[i] combinationSumMy(candidates, every, final, target - candidates[i], i); //对新target(target - candidate[i]) 进行DFS every.pop_back(); //回溯 } } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { std::sort(candidates.begin(), candidates.end()); vector<int> every; vector<vector<int> > final; combinationSumMy(candidates, every, final, target, 0); return final; } };
一开始写得版本是错误的,没有滤重,对比下面这个错误版本,可以更清晰第认识到start起到的作用。start使得每次选到的candidate[i]都只能为两种情况,要么是start本身, 要么是start右边的数。
//错误版本 class Solution { public: void combinationSumMy(vector<int> &candidates, vector<int> &every, vector<vector<int> > & final, int target) { if (target < 0) { return; }else if (target == 0) { final.push_back(every); return; }else { for (int i = 0; i < candidates.size(); ++i) { every.push_back(candidates[i]); combinationSumMy(candidates, every, final, target - candidates[i]); every.pop_back(); } } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { std::sort(candidates.begin(), candidates.end()); vector<int> every; vector<vector<int> > final; combinationSumMy(candidates, every, final, target); return final; } };
2,2,3,
2,3,2,
3,2,2,
7,
因为输出有重复,所以增加了start,用来避免重复输出,每次的candidate都是start本身或者start右边的数。