AcWing 717. 简单斐波那契
原题链接
中等
迭代法
#include<iostream>
using namespace std;
const int N = 50;
int A[N];
int n;
int main()
{
cin >> n;
int a = 0, b = 1;
A[0] = 0, A[1] = 1;
int c = 0;
for(int i = 2; i < n;i++)
{
c = a + b;
a = b, b = c;
A[i] = c;
}
for(int i = 0;i < n;i++)
printf("%d ",A[i]);
return 0;
}
递归写法
#include<iostream>
using namespace std;
const int N = 50;
int a[N];
int n;
int FeiBo(int n)
{
if(n == 0) return 0;
if(n == 1) return 1;
if(a[n]) return a[n]; // a[n]已经计算过
else return a[n] = FeiBo(n - 1) + FeiBo(n - 2);
}
int main()
{
cin >> n;
a[0] = 0, a[1] = 1;
FeiBo(n);
for(int i = 0;i < n;i++)
cout << a[i] << " " ;
return 0;
}