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;
}

 

相关文章:

  • 2022-12-23
  • 2021-04-25
猜你喜欢
  • 2022-01-17
  • 2021-11-11
  • 2022-12-23
  • 2021-09-22
  • 2021-09-08
  • 2021-09-05
  • 2022-02-09
相关资源
相似解决方案