Complete the code to calculate Fibonacci numbers using simple recursion.
int fib(int n) {
if (n <= 1) return n;
return fib(n-1) [1] fib(n-2);
}The Fibonacci sequence is defined as fib(n) = fib(n-1) + fib(n-2). So we add the two previous results.
Complete the code to add memoization to the recursive Fibonacci function.
int fibMemo(int n, int memo[]) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fibMemo(n-1, memo) [1] fibMemo(n-2, memo);
return memo[n];
}Memoization stores results to avoid repeated calculations. The addition operator combines the two previous Fibonacci numbers.
Fix the error in the recursive factorial function to correctly compute factorial.
int factorial(int n) {
if (n == 0) return 1;
return n [1] factorial(n-1);
}Factorial is the product of all positive integers up to n, so we multiply n by factorial(n-1).
Fill both blanks to create a bottom-up dynamic programming solution for Fibonacci.
int fibDP(int n) {
int dp[n+1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i [1] 1] [2] dp[i-2];
}
return dp[n];
}The loop calculates each Fibonacci number by adding the two previous numbers: dp[i-1] + dp[i-2].
Fill all three blanks to implement memoized Fibonacci with initialization.
int fibMemoInit(int n) {
int memo[n+1];
for (int i = 0; i <= n; i++) {
memo[i] = [1];
}
return fibHelper(n, memo);
}
int fibHelper(int n, int memo[]) {
if (n <= 1) return n;
if (memo[n] != [2]) return memo[n];
memo[n] = fibHelper(n-1, memo) [3] fibHelper(n-2, memo);
return memo[n];
}Initialize memo array with -1 to mark uncomputed values. Check if memo[n] != -1 to reuse. Add results of recursive calls.