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]
]
测试代码:
class Solution {
void find_answer(vector<int> candidates,vector<vector<int> >& solutions,vector<int>& solution,int target,int begin)
{
if (!target) {
solutions.push_back(solution);
return;
}
for (int i = begin; i != candidates.size() && target >= candidates[i]; ++i)
if (i == begin || candidates[i] != candidates[i - 1]) {
solution.push_back(candidates[i]);
find_answer(candidates,solutions, solution, target - candidates[i], i + 1);
solution.pop_back();
}
}
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int> > solutions;
vector<int> solution;
sort(candidates.begin(),candidates.end());
find_answer(candidates,solutions,solution,target,0);
return solutions;
}
};
性能:
参考答案:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> res;
vector<int> path;
helper(candidates, 0, target, res, path);
return res;
}
private:
void helper(vector<int>& candidates, int pos , int target, vector<vector<int>>& res, vector<int>& path) {
if (target == 0) {
res.push_back(path);
return;
}
if (pos >= candidates.size() || candidates[pos] > target) {
return;
}
int count = 1;
while (pos + count < candidates.size() && candidates[pos] == candidates[pos + count]) {
count++;
}
for (int i = 1; i <= count; i++) {
path.push_back(candidates[pos]);
helper(candidates, pos + count, target - i * candidates[pos], res, path);
}
for (int i = 1; i <= count; i++) {
path.pop_back();
}
helper(candidates, pos + count, target, res, path);
return;
}
};