int i放在全局和函数中定义结果不同,但除函数外未用i,不知道为什么,请大佬解惑!以下为wa代码
#include <bits/stdc++.h>
using namespace std;
int n;
int a[10001]={1};
int i=0;
void print (int t)
{
cout << n << "=" ;
for(int j=1;j<t;j++)
cout << a[j] << "+";
cout << a[t];
cout << endl;
}
void dfs(int s,int t)
{
for(i=a[t-1];i<=s;i++)
{
if(i<n)
{
a[t]=i;
s-=i;
if(s==0)
print(t);
else dfs(s,t+1);
s+=i;
}
}
}
int main()
{
cin >> n;
dfs(n,1);
return 0;
}
但把int i=0移到dfs中,如下就能AC了,不知道为什么
#include <bits/stdc++.h>
using namespace std;
int n;
int a[10001]={1};
void print (int t)
{
cout << n << "=" ;
for(int j=1;j<t;j++)
cout << a[j] << "+";
cout << a[t];
cout << endl;
}
void dfs(int s,int t)
{
int i=0;
for(i=a[t-1];i<=s;i++)
{
if(i<n)
{
a[t]=i;
s-=i;
if(s==0)
print(t);
else dfs(s,t+1);
s+=i;
}
}
}
int main()
{
cin >> n;
dfs(n,1);
return 0;
}