40. 組合總和 II
阿新 • • 發佈:2018-12-10
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的每個數字在每個組合中只能使用一次。
說明:
所有數字(包括目標數)都是正整數。 解集不能包含重複的組合。 示例 1:
輸入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集為:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
示例 2:
輸入: candidates = [2,5,2,1,2], target = 5, 所求解集為: [ [1,2,2], [5] ]
注意條件:
- 給定陣列的所有值必須是正整數.(意味著我們加corner case invalid check的 時候要檢查T)
- 答案陣列中的值必須為升序排列.(我們要對陣列進行排序)
- 最終答案不能包含重複陣列.
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
vector<vector<int>> res;
if(candidates. size() == 0 || target < 0) {
return res;
}
vector<int> curr;
sort(candidates.begin(), candidates.end());
BackTracking(res, curr, candidates, target, 0);
return res;
}
void BackTracking(vector<vector<int>>& res, vector< int> curr, vector<int> candidates,int target, int level) {
if(target == 0) {
res.push_back(curr);
return;
} else if(target < 0) {
return;
}
for(int i = level; i < candidates.size(); i++) {
target -= candidates[i];
curr.push_back(candidates[i]);
BackTracking(res, curr, candidates, target, i + 1);
curr.pop_back();
target += candidates[i];
while(i < candidates.size() - 1 && candidates[i] == candidates[i + 1]) {
++i;
}
}
}
};