题目
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]
]
分析
这题与第39题的不同点如下
- 不能重复使用同一个数字,这一点可以在递归的时候将start参数不断提前来实现
- 答案中的数字的顺序是从前面的数字往后的,所以在最后要将答案反转
- candidates中可能会有重复的数字,所以枚举数字的时候要跳过已经枚举过的数字
实现
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> ans;
sort(candidates.begin(), candidates.end());
ans = solve(candidates, target, 0);
for(int i=0; i<ans.size(); i++){
reverse(ans[i].begin(), ans[i].end());
}
return ans;
}
private:
vector<vector<int>> solve(vector<int>& candidates, int target, int start) {
vector<vector<int>> ans;
for(int i=start; i<candidates.size(); i++){
if(target-candidates[i]<0){
continue;
}
else if(target-candidates[i]==0){
ans.push_back({candidates[i]});
}
else{
vector<vector<int>> tmp;
tmp = solve(candidates, target-candidates[i], i+1);
for(auto v: tmp){
v.push_back(candidates[i]);
ans.push_back(v);
}
}
while(i+1<candidates.size() && candidates[i]==candidates[i+1])
i++;
}
return ans;
}
};
思考
这里也删掉了第39题中没用的两行代码。总体来说这道题做得很舒服=_=。