Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5
and target 8
,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
class Solution {
public:
void combinationSumInternal(vector<int> &candidates, vector<int> currentnums, int current,
int target, int start, int end, vector<vector<int> > &results) {
if(current == target)
{
results.push_back(currentnums);
return;
}
if(current > target)
return;
for(int ii = start; ii < end; ii ++) {
currentnums.push_back(candidates[ii]);
combinationSumInternal(candidates, currentnums, current + candidates[ii], target, ii + 1, end, results);
currentnums.pop_back();
// In order to make things unique.
while(ii < end - 1 && candidates[ii] == candidates[ii + 1]) ii ++;
}
}
vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {
vector<vector<int> > results;
vector<int> currentnums;
vector<int> newcand;
for(int ii = 0; ii < candidates.size(); ii ++) {
if(candidates[ii] <= target)
newcand.push_back(candidates[ii]);
}
sort(newcand.begin(), newcand.end());
combinationSumInternal(newcand, currentnums, 0, target, 0, newcand.size(), results);
return results;
}
};