递推做法
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main() {
int f[46];
f[1] = 0;
f[2] = 1;
int n;
cin >> n;
for (int i = 3; i <= n; i++)
{
f[i] = f[i - 1] + f[i - 2];
}
for (int i = 1; i <= n; i++) {
cout << f[i] << " ";
}
return 0;
}
动态优化写法:
相当于一个滚动数组的雏形
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main() {
int a = 0, b = 1;
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cout << a << " ";
int f = a + b;
a = b, b = f;
}
return 0;
}