Recursive Fibonacci

前端 未结 13 1692
情歌与酒
情歌与酒 2020-12-07 18:52

I\'m having a hard time understanding why

#include 

using namespace std;

int fib(int x) {
    if (x == 1) {
        return 1;
    } else {
         


        
13条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 19:47

    I think that all that solutions are inefficient. They require a lot of recursive calls to get the result.

    unsigned fib(unsigned n) {
        if(n == 0) return 0;
        if(n == 1) return 1;
        return fib(n-1) + fib(n-2);
    }
    

    This code requires 14 calls to get result for fib(5), 177 for fin(10) and 2.7kk for fib(30).

    You should better use this approach or if you want to use recursion try this:

    unsigned fib(unsigned n, unsigned prev1 = 0, unsigned prev2 = 1, int depth = 2)     
    {
        if(n == 0) return 0;
        if(n == 1) return 1;
        if(depth < n) return fib(n, prev2, prev1+prev2, depth+1);
        return prev1+prev2;
    }
    

    This function requires n recursive calls to calculate Fibonacci number for n. You can still use it by calling fib(10) because all other parameters have default values.

提交回复
热议问题