題目
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題中沒用的兩行代碼。總體來說這道題做得很舒服=_=。