斐波那契数列(Fibonacci sequence),又称黄金分割数列,因数学家莱昂纳多·斐波那契(Leonardo Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”,指的是这样一个数列:1、1、2、3、5、8、13、21、34、……在数学上,斐波那契数列以如下被以递推的方法定义:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
首先看第一种:
static int Fib(int n)
{
if (n <= 0)
return 0;
if (n < 3)
return 1;
return Fib(n - 1) + Fib(n - 2);
}
在return 时,调用了两次Fib,显然它的时间复杂度是O(n²)
第二种:
static int Fib(int first,int second,int n)
{
if (n <= 0)
return 0;
if (n < 3)
return 1;
else if (n == 3)
return first + second;
return Fib(second, first+second,n-1);
}
它的时间复杂度是优于第一种的,因为它时间复杂度为:O(n)
第三种,公式法
static int Fit(int n)
{
if (n <= 0)
return 0;
if (n < 3)
return 1;
double sqrt5=Math.Sqrt(5);
return (int)((Math.Pow((1 + sqrt5) / 2, n) - Math.Pow((1 - sqrt5) / 2, n)) / sqrt5);
}