LeetCode40. Combination Sum II
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.
- 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] ]
void isok(vector<int>& candidates, vector<vector<int>>& result, int target, int begin, vector<int> tmp) {
if (target == 0) {
result.push_back(tmp);
}
else {
for (int i = begin; i < candidates.size(); i++) {
if (candidates[i] > target) {
break;
}
if (i == begin || candidates[i] != candidates[i - 1]) {
tmp.push_back(candidates[i]);
isok(candidates, result, target - candidates[i], i + 1, tmp);
tmp.pop_back();
}
}
}
}
代码:class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> result;
vector<int> tmp;
isok(candidates, result, target, 0, tmp);
return result;
}
void isok(vector<int>& candidates, vector<vector<int>>& result, int target, int begin, vector<int> tmp) {
if (target == 0) {
result.push_back(tmp);
}
else {
for (int i = begin; i < candidates.size(); i++) {
if (candidates[i] > target) {
break;
}
if (i == begin || candidates[i] != candidates[i - 1]) {
tmp.push_back(candidates[i]);
isok(candidates, result, target - candidates[i], i + 1, tmp);
tmp.pop_back();
}
}
}
}
};