Leetcode: 40. Combination Sum II(Week13, Medium)
阿新 • • 發佈:2019-01-26
Leetcode 40
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]
]
- 題意:給出一個數字序列和目標值,要求從數字序列中得到所有組合(組合不能重複),且序列中每個數字只能使用一次,最終使得每個組合的和等於目標值
- 思路:與Leetcode39 的Combination Sum思路差不多,只不過要做點修改:在主函式中迴圈呼叫遞迴函式,將遞迴函式中for迴圈的迴圈變數初始化+1,以避免重複使用數字序列中的數字。但是由於示例中的數字序列是有重複數字的,這樣會導致最終的組合中可能會有重複答案,所以使用了set來進行去重操作。
- 程式碼如下:
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
//candidates.erase(unique(candidates.begin(), candidates.end()), candidates.end());
set<vector<int>> s;
vector<vector<int>> result;
vector <int> temp_result;
for (int i = 0; i < candidates.size(); i++) {
temp_result.push_back(candidates[i]);
solve_Combination_Sum(candidates, s, temp_result, target-candidates[i], i);
temp_result.pop_back();
}
for (auto it = s.begin(); it != s.end(); it++) {
result.push_back(*it);
}
return result;
}
void solve_Combination_Sum(vector<int>& candidates, set<vector<int>>& result, vector<int>& out, int target, int index) {
if (target < 0) return;
if (target == 0) {
result.insert(out);
}
for (int i = index+1; i < candidates.size(); i++) {
out.push_back(candidates[i]);
solve_Combination_Sum(candidates, result, out, target-candidates[i], i);
out.pop_back();
}
}
};
以上內容皆為本人觀點,歡迎大家提出批評和指導,我們一起探討!