I eventually want to get the hang of dynamic programming but before that, I am having a hard time understanding the flow of this. I understand recursion but I'm having trouble understanding the flow of this:
function fib(n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(3));
if I have a small integer of 3, it does not pass those 2 conditionals so it hits return fib(n-1)+fib(n-2); So to my understanding, that will go through the first part of that first: fib(n-1) (3-1 = 2)... 2 does not satisfy either of those conditionals so it runs fib(n-1) (2-1 = 1). 1 DOES satisfy one of the conditionals so it returns 1 and breaks that part of it.
Now to to the next part: fib(n-2) . (3-2 = 1). 1 does satisfy one of the conditionals so it returns 1 .
So in the end, isn't that returning 1 + 1 ?
I'm not sure where I'm going wrong in my understanding.
fiblikefib(4)will result in multiple (eventual) reductions to sums offib(1).fib(4). What does the tree of recursive calls look like then? You'll see that you can indeed get a result greater than 2.fib(2)returnsfib(2 -1) + fib(2 - 2) = 1 + 0. I think it's easier to write it as math function expansion:fib(3) = fib(2) + fib(0) = (fib(1) + fib(0)) + fib(0) = 2