首页 > 代码库 > 斐波那契数列

斐波那契数列

递归:

int fib1(int n)  
{  
    if(n<=0)  
      return 0;  
    if(n==1)  
      return 1;  
    return fib1(n-1)+fib1(n-2);  
} 

非递归:

int fib2(int n)
{
    int result[2] = {0,1};
    if(n < 2)
        return result[n];
    int fibOne = 0;
    int fibTwo = 1;
    int fibN   = 0;
    int i = 0;
    for(i = 2; i <= n; i++)
    {
        fibN = fibOne + fibTwo;
        
        fibOne = fibTwo;
        fibTwo = fibN;
    }
    
    return fibN;
}

时间复杂度为O(n)。

斐波那契数列