Complete the code to return the nth Fibonacci number using simple recursion.
public int fib(int n) {
if (n <= 1) {
return n;
}
return fib(n - 1) + fib([1]);
}The Fibonacci number is calculated by adding fib(n-1) and fib(n-2). So the blank should be n - 2.
Complete the code to use memoization for Fibonacci to avoid repeated calculations.
public int fibMemo(int n, int[] memo) {
if (n <= 1) {
return n;
}
if (memo[n] != 0) {
return memo[n];
}
memo[n] = fibMemo(n - 1, memo) + fibMemo([1], memo);
return memo[n];
}Memoization stores results of fib(n-1) and fib(n-2). The second call must be fibMemo(n - 2, memo).
Fix the error in the bottom-up Fibonacci implementation to correctly fill the dp array.
public int fibBottomUp(int n) {
if (n <= 1) {
return n;
}
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[[1]];
}
return dp[n];
}The Fibonacci number at position i is the sum of dp[i-1] and dp[i-2]. So the blank must be i - 2.
Fill both blanks to complete the recursive function with memoization for the coin change problem.
public int coinChange(int[] coins, int amount, int[] memo) {
if (amount == 0) {
return 0;
}
if (amount < 0) {
return -1;
}
if (memo[amount] != 0) {
return memo[amount];
}
int min = Integer.MAX_VALUE;
for (int coin : coins) {
int res = coinChange(coins, amount - coin, memo);
if (res != -1 && res [1] min) {
min = res + 1;
}
}
memo[amount] = (min == Integer.MAX_VALUE) ? -1 : min;
return memo[amount];
}We want the minimum number of coins, so we update min if res is less than min. The blank should be <.
Fill all three blanks to complete the dynamic programming solution for the longest common subsequence problem.
public int lcs(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + [1];
} else {
dp[i][j] = Math.[2](dp[i - 1][j], dp[i][[3]]);
}
}
}
return dp[m][n];
}When characters match, add 1 to dp[i-1][j-1]. Otherwise, take the max of dp[i-1][j] and dp[i][j-1]. So blanks are 1, max, and j - 1.
