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: vector<vector<int> > combinationSum(vector<int> &candidates, int target) { results.clear(); vector<int> result; sort(candidates.begin(), candidates.end()); dfs(candidates, result,target, 0); return results; } void dfs(vector<int> &candidates, vector<int> &result, int target, int depth) { if(candidates[depth] > target || depth == candidates.size()) return; result.push_back(candidates[depth]); if(candidates[depth] == target) { results.push_back(result); result.pop_back(); return; } dfs(candidates,result, target-candidates[depth], depth); //选择该元素,可以重复选择,所以depth不加 result.pop_back(); dfs(candidates,result, target, depth+1); //注意回溯后depth+1 } private: vector<vector<int> > results; };
39. Combination Sum (Recursion)
原文:http://www.cnblogs.com/qionglouyuyu/p/4855325.html