题目描述
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int> > res;
vector<int> path;
int accumulate(vector<int> path){
int sum;
for(int i = 0; i < path.size(); i++){
sum += path[i];
}
return sum;
}
void backtrace(vector<int>& candidates, int target, int startindex){
//if(accumulate(path.begin(), path.end(),0) == target){
if(accumulate(path) == target){
res.push_back(path);
return ;
}else if(path.size() == candidates.size()){
return ;
}
for(int i = startindex; i < candidates.size(); i++){
path.push_back(candidates[i]);
backtrace(candidates, target, i);
path.pop_back();
}
}//void
vector<vector<int> > combinationSum(vector<int>& candidates, int target) {
res.clear();
path.clear();
backtrace(candidates, target, 0);
return res;
}
int main(){
vector<int> candidates;
int n,m;
cin>>n;
while(n--){
cin>>m;
candidates.push_back(m);
}
int target;
cin>>target;
vector<vector<int> > result = combinationSum(candidates, target);
for(int i = 0; i < result.size(); i++){
for(int j = 0; j < result[i].size(); j++){
cout<<result[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
事实证明纯套模板还是不太可能的,不同的题之间总会有差别,还是要按照三步骤分析,区分同层枚举和向下递归。
标签:总数,target,int,力扣,vector,candidates,回溯,path,size From: https://www.cnblogs.com/satsuki26681534/p/18059212