《数据结构:邓俊辉版》——斐波那契数列

1、传统方法

int Fibonacci(int n)
{
    if (n <= 1)
    {
        return 1;
    }

    return Fibonacci(n - 1) + Fibonacci(n - 2);
}

这个方法时间复杂度太差了,在O(2^n),所以如果你这么解答面试官的问题,几乎得不了什么分。

2、改进

int Fibonacci2(int n, int& result)
{
    if (n == 2)
    {
        result = 1;
        return 1;
    }

    int nTmp;
    result = Fibonacci2(n - 1, nTmp);
    return result + nTmp;
}

int Fibonacci3(int n, int& result)
{
    if (n == 0)
    {
        result = 1;
        return 0;
    }

    int nTmp;
    result = Fibonacci2(n - 1, nTmp);
    return result + nTmp;
}

3、改为非递归

int Fibonacci4(int n)
{
    int f = 1;
    int g = 0;
    while (0 < n--)
    {
        g += f;
        f = g - f;
    }
    return g;
}

猜你喜欢

转载自www.cnblogs.com/predator-wang/p/11769075.html