Complete the code to implement a simple recursive factorial function.
int factorial(int n) {
if (n == 0) return 1;
return n * factorial([1]);
}The factorial function calls itself with n - 1 to reduce the problem size until it reaches 0.
Complete the code to implement memoization for Fibonacci numbers.
int fib(int n, int[] memo) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
memo[n] = fib([1], memo) + fib(n - 2, memo);
return memo[n];
}The Fibonacci number at n is the sum of fib(n-1) and fib(n-2). Memoization stores results to avoid repeated work.
Fix the error in the greedy coin change algorithm to pick the largest coin first.
int coinChange(int amount, int[] coins) {
int count = 0;
for (int i = 0; i < coins.length; i++) {
while (amount >= coins[[1]]) {
amount -= coins[[1]];
count++;
}
}
return count;
}To pick the largest coin first, iterate coins in reverse order using coins.length - 1 - i.
Fill both blanks to create a dynamic programming solution for the 0/1 knapsack problem.
for (int i = 1; i <= n; i++) { for (int w = 1; w <= W; w++) { if (weights[i - 1] <= w) { dp[i][w] = Math.max(dp[i - 1][w], dp[i - 1][[1]] + values[i - 1]); } else { dp[i][w] = dp[i - 1][[2]]; } } }
The dp table stores max value for weight w. When including item i, subtract its weight from w. Otherwise, keep previous value at w.
Fill all three blanks to implement a bottom-up DP solution for the Longest Common Subsequence (LCS).
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[[1]][[2]] + 1; } else { dp[i][j] = Math.max(dp[[3]][j], dp[i][j - 1]); } } }
When characters match, add 1 to dp[i-1][j-1]. Otherwise, take max of dp[i-1][j] and dp[i][j-1].
