剑指Offer系列-面试题9:斐波那契数列

题目:写一个函数,输入n,求斐波那契(Fibonacci)数列的第n项。

效率很低的解法(递归实现):

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

从f(0)、f(1)、f(2)由低往高算:
#include 

using namespace std;

long long Fibonacci(unsigned n)
{
    int result[2] = {0, 1};
    if(n < 2)
        return result[n];
    long long fibNMinusOne = 1;
    long long fibnMinusTwo = 0;
    long long fibN = 0;
    for(unsigned int i = 2; i <= n; ++i)
    {
        fibN = fibNMinusOne + fibnMinusTwo;

        fibnMinusTwo = fibNMinusOne;
        fibNMinusOne = fibN;
    }
    return fibN;
}

int main()
{
    cout << Fibonacci(3) << endl;
    cout << Fibonacci(5) << endl;
    cout << Fibonacci(10) << endl;
    return 0;
}


你可能感兴趣的:(剑指Offer,剑指Offer)