#include<bits/stdc++.h>
using namespace std;
void solve(int ind,vector<int>&ar,int sum,int target,int nums[],int n)
{
//cout<<sum<<" ";
if(ind == n)
{
if(sum == target)
{
cout<<2<<endl;
for(auto it:ar)
{
cout<<it<<" ";
}
return ;
}
}
ar.push_back(nums[ind]);
sum+=nums[ind];
solve(ind+1,ar,sum,target,nums,n);
sum-=nums[ind];
ar.pop_back();
solve(ind+1,ar,sum,target,nums,n);
}
int main()
{
int nums[] = {1,2,1};
int target = 2;
int n = 3;
vector<int>ar;
int sum = 0;
solve(0,ar,0,target,nums,n);
}
代码在在线编译器和VSCode中给出分段错误,它不显示任何输出。我不知道这段代码出了什么问题,我已经试着弄清楚很长时间了。
错误回溯:
/bin/bash: line 1: 18 Segmentation fault timeout 15s ./f9f11492-657e-4e6a-b05c-ffc40f6540ea < f9f11492-657e-4e6a-b05c-ffc40f6540ea.in
尝试将return
语句移出if
块。就像其他人提到的,问题是,如果ind == n
但sum
和target
不匹配,则不会发生return
,然后nums[ind]
会给出超出界限的错误。
应该是
//cout<<sum<<" ";
if(ind == n)
{
if(sum == target)
{
cout<<2<<endl;
for(auto it:ar)
{
cout<<it<<" ";
}
}
return ;
}
.... <remaining code follows>