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?
2^N
N
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.
?
n, f(n-1) . , n f(n-1) .., , n, 2 ^ n ( ). , f(n-1) . f(n-2) f(n-1),....
n
f(n-1)
f(n-2)
( , , ), , f(0), . , , - , f(n-1), f(n-2),..., f(1), f(0). O (n) . ( ).
f(0)
f(1)
Source: https://habr.com/ru/post/1627368/More articles:How can I get the url on behalf of the route in C # using asp.net mvc and razor pattern mechanism? - c #How to create placeholder variables in a catch try block in Clojure - clojureUpdating Jira tickets from Jenkins workflow (jenkinsfile) - jenkinsRequest Parameters Grails RestBuilder - grailscron для каждых 30 секунд в кварцевом планировщике? - javaSiam drill network 220 in Keras - deep-learningBash IF statement: string comparison of command output is always false - bashParse Push JSON data output on Android - jsonmatplotlib - pandas - No xlabel and xticks for double axes in trimmed shapes - pythonКак получить следующий маршрут маршрута в приложении Express - javascriptAll Articles