Given a set of candidate numbers (C) (without duplicates) 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.
- 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]]
解答:
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> ans; if(candidates.size() == 0) return ans; sort(candidates.begin(), candidates.end()); vector<int> temp; findAns(ans, temp, candidates, 0, target); return ans; } private: void findAns(vector<vector<int>>& ans, vector<int>& temp, vector<int>& c,int index, int nowSum) { if(nowSum <= 0) { if(nowSum == 0) { ans.push_back(temp); } return; } int len = c.size(); for(int i = index; i < len; ++i) { if(c[i] > nowSum) break; temp.push_back(c[i]); findAns(ans, temp, c, i, nowSum - c[i]); temp.pop_back(); } } };