1

So this is some code to calculate the Fibonacci sequence with memoization. What confuses me is when we check if memo[i]==0. I understand that Java arrays are initialized to zero and thus if memo[i] == 0 this may mean that the computation for memo[i] has not yet occured. However, one of the return values for this fibonacci function is 0. So doesn't this mean that let's say if fib(3)=0 (I know it doesn't but just for the sake of arguement) then everytime we have fib(3) we would wind up recomputing fib(3) because the check is if(memo[i] == 0) right? And if that is the case why can we use if(memo[i] == 0) in this particular code and not wind up recomputing a bunch of values?

int fibonacci(int n){
  return fibonacci(n, new int[n+1]);
}

int fibonacci(int i, int[] memo) {
  if(i == 0 || i == 1) return i;

  if(memo[i] == 0){ //This line does not make sense to me
    memo[i] = fibonacci(i - 1, memo) + fibonacci(i - 2, memo);
  }
  return memo[i];
}
dtheman94
  • 31
  • 5

2 Answers2

1

Since the only case where fib(i) should return 0 is when i = 0, then the test if (memo[i] == 0) is ok---it is never called for a value where 0 is an ambiguous result because of the first line of the function: if (i == 0.

Note what I think is more puzzling is why is the memoization array created in the wrapper call? Yes, the memoization saves computation for a given call, but all that optimization is lost between successive calls to the function.

Matthew Burke
  • 2,295
  • 17
  • 14
0

if(memo[i]==0)

That if block implies that if fibonacci(n) has not already been computed (in which case the value in the i index will be 0), compute the value of fibonacci(n) and cache, but if it has already been computed and stored/cached (in which case the value in the i index would not be 0), do not compute again.

The reason for this is because, int array values are by default initialized to 0. You can see how here: Any shortcut to initialize all array elements to zero?

kingified
  • 195
  • 1
  • 2
  • 18