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, the operator between the two recursive calls is '+'.
Complete the code to add memoization to the recursive Fibonacci function.
int fibMemo(int n, vector<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 Fibonacci sum remains the same, so '+' is used.
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 the operator must be '*'.
Fill both blanks to create a bottom-up dynamic programming solution for Fibonacci.
int fibDP(int n) {
vector<int> dp(n+1, 0);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i-[1]] [2] dp[i-2];
}
return dp[n];
}In bottom-up DP for Fibonacci, dp[i] = dp[i-1] + dp[i-2]. So blanks are '1' and '+'.
Fill all three blanks to implement memoized recursion for the Fibonacci sequence.
int fibMemoized(int n, vector<int>& memo) {
if (n <= 1) return n;
if (memo[[1]] != -1) return memo[[2]];
memo[n] = fibMemoized(n-1, memo) [3] fibMemoized(n-2, memo);
return memo[n];
}We check and return memo[n], so blanks 1 and 2 are 'n'. The operator is '+' for Fibonacci sum.
