What is the cosmic complexity of the next function and how?

Consider the following recursive function.

int f(int n){
   if(n<=0) return 1; return f(n-1)+f(n-1);
}

They say that although there are 2^N(2 on N) calls, only calls Nexist at a given time. Can someone explain how?

+4
source share
2 answers

Of course. Part of the difficulty is in another part:

return f(n-1)+f(n-1)

This caused two calls at n-1 for each call at n . However, pay attention to the evaluation procedure:

call f(n-1) ... left side
save the value as temp1
call f(n-1) ... right side
add the value to temp1
return that value

, - . n . , f (2) ​​:

call f(2)
n isn't <= 0 ...
    call f(1) ... left
    n isn't <= 0 ...
        call f(0) ... left | left
        n <= 0; return 1
        save the 1
        call f(0) ... left | right
        n <=0; return 1
        add the 1 to the temp value;
        return 2
    save the 2
    call f(1) ... right
        call f(0) ... left | left
        n <= 0; return 1
        save the 1
        call f(0) ... left | right
        n <=0; return 1
        add the 1 to the temp value;
        return 2
    add this 2 to the temp value, making 4
    return the 4
done ...

n + 1 (. ), 2 ^ (n + 1) -1. (n + 1 n), 0 1.

?

+2

n, f(n-1) . , n f(n-1) .., , n, 2 ^ n ( ). , f(n-1) . f(n-2) f(n-1),....

( , , ), , f(0), . , , - , f(n-1), f(n-2),..., f(1), f(0). O (n) . ( ).

+1

Source: https://habr.com/ru/post/1627368/


All Articles