剑指offer:面试题9,斐波那契数列
2016-11-07 19:15
323 查看
递归算法
#include<stdio.h>
#include <stdlib.h>
int fibonacci(int n)
{
if (n<=0)
{
return 0;
}
if (n==1)
{
return 1;
}
return fibonacci(n-1)+fibonacci(n-2);
}
int main()
{
int n=0;
int sum=0;
scanf("%d",&n);
sum=fibonacc(n);
printf("%d\n",sum);
system("pause");
return 0;
}
递归算法算比较大的数列时重复调用次数太多效率极低
迭代算法
int fibonacc(int n)
{
int i=0;
int a=1;
int b=1;
int c=1;
while ((n>2)&&(i<n-2))
{
c=a+b;
a=b;
b=c;
i++;
}
return c;
}
int main()
{
int n=0;
int sum=0;
scanf("%d",&n);
sum=fibonacc(n);
printf("%d\n",sum);
system("pause");
return 0;
}
#include<stdio.h>
#include <stdlib.h>
int fibonacci(int n)
{
if (n<=0)
{
return 0;
}
if (n==1)
{
return 1;
}
return fibonacci(n-1)+fibonacci(n-2);
}
int main()
{
int n=0;
int sum=0;
scanf("%d",&n);
sum=fibonacc(n);
printf("%d\n",sum);
system("pause");
return 0;
}
递归算法算比较大的数列时重复调用次数太多效率极低
迭代算法
int fibonacc(int n)
{
int i=0;
int a=1;
int b=1;
int c=1;
while ((n>2)&&(i<n-2))
{
c=a+b;
a=b;
b=c;
i++;
}
return c;
}
int main()
{
int n=0;
int sum=0;
scanf("%d",&n);
sum=fibonacc(n);
printf("%d\n",sum);
system("pause");
return 0;
}
相关文章推荐
- 《剑指offer》面试题9:斐波那契数列
- 剑指offer面试题 斐波那契数列
- (剑指Offer)面试题9:斐波那契数列
- 剑指Offer面试题9[斐波那契数列]
- 剑指Offer_面试题09_斐波那契数列
- 《剑指Offer》学习笔记--面试题9:斐波那契数列
- 剑指offer面试题9——矩形框覆盖(递归改循环,斐波那契数列)
- 《剑指offer》【面试题九:斐波那契数列】
- 剑指offer面试题9 斐波那契数列
- 剑指offer:面试题9,斐波那契数列
- 剑指offer:面试题9,斐波那契数列
- 剑指offer_面试题9_斐波那契数列
- 剑指offer:面试题9,斐波那契数列
- 《剑指offer》面试题10:斐波那契数列(含矩阵乘法解法)
- 剑指offer-面试题 9 斐波那契数列
- 剑指Offer面试题10:斐波那契数列
- 剑指Offer学习之面试题9 : 斐波那契数列
- 《剑指Offer》面试题九之斐波那契数列
- 剑指Offer----面试题九:斐波那契数列
- 剑指offer——面试题9:斐波那契数列