斐波纳契数列以如下被以递归的方法定义:
F0=0,F1=1
Fn=F(n-1)+F(n-2)(n>=2,n∈N*)
1. 最简单的求解Fibonacci数列的方法,就是递归的求解,最好的时间复杂度为O(n)。
2. Fibonacci数列还有他自己的产生式:F(n)=(√5/5)*{[(1+√5)/2]^n - [(1-√5)/2]^n},这里牵涉到求幂问题,可以利用分治的方法来求解,复杂度O(lgn)
3 . 此外Fibonacci数列还可以利用矩阵法,sums of "shallow" diagonals in Pascal's triangle形式求解
这里我们采用最简单的递归求解的方式,递归的话自下而上和自上而下空间复杂度是不同的。
#include "stdafx.h"
#include<iostream>
using namespace std;
int Fibonacci(int n)//缺点是需要申请n个整型空间
{
int *result = (int *)malloc(sizeof(int)*n+1);
result[0] = 0;
result[1] = 1;
if(n<2)
return result[n];
for(int i=2;i<=n;i++)
result[i] = result[i-1]+result[i-2];
return result[n];
}
int Fibonacci2(int n)//不需要申请O(n)的空间
{
if(n == 0)
return 0;
if(n == 1)
return 1;
int first = 0;
int second = 1;
int result = 0;
for(int i=2;i<=n;i++)
{
result = first + second;
first = second;
second = result;
}
return result;
}
int main()
{
cout<<Fibonacci2(12);
getchar();
return 0;
}