"Data Structure: Deng Junhui Edition" - Fibonacci number

1, the traditional method

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

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

This method is time complexity bad, in O (2 ^ n), so if you so answer the interviewer's question, what almost had zero points.

2. Improve

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, into a non-recursive

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

 

Guess you like

Origin www.cnblogs.com/predator-wang/p/11769075.html