简体   繁体   中英

Recursive function inside a simple loop time complexity

Why is it that inside a for loop and calling a recursive function results to the time complexity of O(2^N) not O(N 2^N) of this code below. Basing on the book CTCI.

void allFib(int n){
    for (int i = 0; i < n; i++) {
        System.out.println(i + ":  "+  fib(i)); 
    }
}

int fib(n){
    if  (n  <=  0)  return 0;
    else if  (n  ==  1)  return 1; 
    return fib(n - 1)  +  fib(n -2);
}

Think of your recursive function as computing values in a tree.

        fib(n)
         /\
        /  \
 fib(n-1)   fib(n-2)

If you look carefully for n = 2 , there are 3 values to be computed which is 2^(1+1) - 1 = 3 where 1 here is the height of the tree as in 2^(h+1)-1

for n = 3 , the height is h = 2

for n = 4 , the height is h = 3

For all n , you need to add all of those: 2^2 - 1 + 2^3 - 1 + 2^4 - 1 + ....2^n - 1 -> is of the order of 2^(n+1)

Hence you get O(2^n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM