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: void visit(vector<int> &candidates, int n, int pos, int target, int sum, vector<vector<int> > &result, vector<int> &buf) { if (sum == target) { result.push_back(buf); return; } if (pos >= n) { return; } int i = 0; while (true) { int temp = sum + candidates[pos]*i; if (temp > target) { break; } else { for (int j = 0; j < i; j++) { buf.push_back(candidates[pos]); } visit(candidates, n, pos+1, target, temp, result, buf); for (int j = 0; j < i; j++) { buf.pop_back(); } } i++; } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { int n = candidates.size(); sort(candidates.begin(), candidates.end()); vector<vector<int> > result; vector<int> buf; int sum = 0; visit(candidates, n, 0, target, sum, result, buf); return result; } };