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]
Subscribe to see which companies asked this question
class Solution {
public:
void findNum(vector<int> &candinates, vector<int> container, vector<vector<int> > &ans, int target, int index, int sum, int n, int flag) {
if(sum == target) {
ans.push_back(container);
return;
}
if(index >= n || sum > target || sum+candinates[index] > target) return;
if(index-1 >= 0 && candinates[index]==candinates[index-1] && flag==true || index==0 || candinates[index]!=candinates[index-1]) {
container.push_back(candinates[index]);
findNum(candinates, container, ans, target, index+1, sum+candinates[index], n, true);
container.erase(container.end()-1);
findNum(candinates, container, ans, target, index+1, sum, n, false);
} else {
findNum(candinates, container, ans, target, index+1, sum, n, false);
}
}
vector<vector<int> > combinationSum2(vector<int> &candinates, int target) {
sort(candinates.begin(), candinates.end());
vector<vector<int> > ans;
vector<int> container;
findNum(candinates, container, ans, target, 0, 0, candinates.size(), false);
return ans;
}
};