What is the space complexity of a recursive fibonacci algorithm?

前端 未结 3 1608
挽巷
挽巷 2020-12-03 17:01

This is the recursive implementation of the Fibonacci sequence from Cracking the Coding Interview (5th Edition)

int fibonacci(int i) {
       if(i == 0) retu         


        
3条回答
  •  Happy的楠姐
    2020-12-03 17:47

    Here's a hint. Modify your code with a print statement as in the example below:

    int fibonacci(int i, int stack) {
        printf("Fib: %d, %d\n", i, stack);
        if (i == 0) return 0;
        if (i == 1) return 1;
        return fibonacci(i - 1, stack + 1) + fibonacci(i - 2, stack + 1);
    }
    

    Now execute this line in main:

    Fibonacci(6,1);
    

    What's the highest value for "stack" that is printed out. You'll see that it's "6". Try other values for "i" and you'll see that the "stack" value printed never rises above the original "i" value passed in.

    Since Fib(i-1) gets evaluated completely before Fib(i-2), there will never be more than i levels of recursion.

    Hence, O(N).

提交回复
热议问题