剑指offer——求斐波那契数列第n项。
之前我写过一些递归与非递归的练习,其中包括了斐波那契数列,感兴趣的可以看一下其他例题。
https://blog.youkuaiyun.com/qq_43606352/article/details/89162421
1.大家对递归算法求斐波那契数列是很熟悉的。分析递归的求解过程就会发现,递归有很严重的效率问题。对于规模较大的问题,递归占用的空间大,花费的时间长。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int Fib(int n)
{
if (n <= 2){
return 1;
}
else
{
return Fib(n - 1) + Fib(n - 2);
}
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("第%d个斐波那契数为%d\n", n,ret );
system("pause");
return 0;
}
2。非递归(迭代)算法。递归之所以慢是进行了大量的重复性工作。那么我们避免重复运算就可以提高效率。我们可以把已经得到的数列中间项保存起来,下次计算时先查找一下就好了。
#include <stdio.h>
#include<stdlib.h>
int Fib(int n)
{
int a = 1, b = 1, c = 1;
if (n < 3){
return c;
}
else{
for (int i = 3; i <= n; i++){
c = a + b;
a = b;
b = c;
}
return c;
}
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = Fib(n);
printf("第%d个斐波那契数为%d\n", n,ret );
system("pause");
return 0;
}