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]
本题利用回溯算法求解,重点在于消除重复。时间:12ms。代码如下:
class Solution { public: void makeCombination(vector<vector<int> > &ans, vector<int> &candidates, vector<int> &tmp, int target, int cur){ for (int i = cur; i < candidates.size(); ++i){ if (0 == target) { ans.push_back(tmp); return; } if (candidates[i] <= target){ tmp.push_back(candidates[i]); makeCombination(ans, candidates, tmp, target - candidates[i], i); tmp.pop_back(); } if (candidates[i] > target){ return; } } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector< vector<int> > ret; sort(candidates.begin(), candidates.end()); if (candidates.empty() || target < candidates[0]) return ret; vector<int> v; makeCombination(ret, candidates, v, target, 0); return ret; } };
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”