Fibonacci数列的函数实现
f(0) = 0,f(1) =1,……..f(n)=f(n-1)+f(n-2)
方法1:递归实现
intFibonacci(int n)
{
if(n ==0)
{
return0;
}
if(n==1)
{
return1;
}
returnFibonacci(n-1)+Fibonacci(n-2);
}
但递归实现比较浪费存储空间,所以做好不用。
方法2:非递归实现
intFibonacci_2(int n)
{
int a[2]={0,1};
int f1 =0;
int f2 =1;
int f3 =0;
if(n<2)
{
returna[n];
}
for(int i=1;i<=n;i++)
{
f3 = f1 + f2;
f1 = f2;
f2 = f3;
if(f3<0)
{
return-1;//判断溢出的情况
}
}
returnf3;
}
方法3:利用备忘录
#include <iostream>
using namespace std;
int t[35];//增加备忘录
int f(int k)
{
if(t[k]!= 0)
return t[k];
if(k ==0 || k == 1)
return 1;
else
return t[k] = f(k-1)+f(k-2);
}
int main()
{
cout<<f(7)<<endl;
return 0;
}
具体应用:一只青蛙一次可以跳上一个台阶也可以跳上两个台阶,问青蛙跳上n个台阶的坑性有多少种情况。f(n) = f(n-1)+f(n-2);分析:假设第一次跳上一个台阶,则可能的情况由后n-1个台阶决定,如果第一次跳2个台阶,的则可能情况为后n-2个台阶决定,则所有情况为:f(n) = f(n-1)+f(n-2),且f(1)=1,f(2)=1。如果将题目改为青蛙可以选择跳上一个台阶也可选2个,以及……n个,则可能的情况为2n-1