#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int>> ans;
vector<int> temp;
void backtrack(vector<int>& candidates, int target, int sum, int startIndex){
if (sum>target){
return ;
}
if (sum==target){
ans.push_back(temp);
return ;
}
for (int i=startIndex; i<candidates.size(); i++){
cout<<i<<" candidates["<<i<<"]->"<<candidates[i]<<", ";
sum+=candidates[i];
temp.push_back(candidates[i]);
backtrack(candidates, target, sum, i);
sum-=candidates[i];
temp.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
backtrack(candidates, target,0,0);
return ans;
}
};
int main(){
vector<vector<int>> ans;
vector<int> array={2,3,6,7};
int target=7;
Solution S;
ans=S.combinationSum(array, target);
for(auto arr:ans){
for(auto element:arr){
cout<<element<<" ";
}
cout<<endl;
}
return 0;
}
结果:
2 2 3
7
Leetcode39. 组合总和--深度优先搜索,回溯算法
最新推荐文章于 2023-03-10 11:49:14 发布