40. 组合总和 II
来自代码随想录
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<vector<int>>res;
vector<int>path;
void backtracking(vector<int>&candidates,int target,int sum, int startIndex){
if (sum == target){
res.push_back(path);
return;
}
//sum+candidates[i] + sum > target,终止遍历(此处进行剪枝)
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++){
if (i>startIndex && candidates[i] == candidates[i-1]) continue;
sum += candidates[i];
path.push_back(candidates[i]);
backtracking(candidates,target,sum,i+1);//不能重复使用
sum -= candidates[i];
path.pop_back();
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end());
backtracking(candidates,target,0,0);
return res;
}
};
int main()
{
vector<int>candidates = {10,1,2,7,6,1,5};
int target = 8;
vector<vector<int>> res = Solution().combinationSum2(candidates,target);
for (int i = 0; i < res.size(); i++){
for (int j = 0; j < res[i].size(); j++){
cout << " " << res[i][j];
}
cout << endl;
}
return 0;
}