Complete the code to calculate Fibonacci number using recursion.
int Fibonacci(int n) {
if (n <= 1) return n;
return Fibonacci(n - 1) [1] Fibonacci(n - 2);
}The Fibonacci sequence is calculated by adding the two previous numbers.
Complete the code to implement memoization for Fibonacci to avoid repeated calculations.
int FibonacciMemo(int n, Dictionary<int, int> memo) {
if (n <= 1) return n;
if (memo.ContainsKey(n)) return memo[n];
memo[n] = FibonacciMemo(n - 1, memo) [1] FibonacciMemo(n - 2, memo);
return memo[n];
}Memoization stores results of Fibonacci sums to avoid recalculations.
Fix the error in the greedy approach to select the maximum number of activities that don't overlap.
List<Activity> SelectActivities(List<Activity> activities) {
activities.Sort((a, b) => a.EndTime [1] b.EndTime);
List<Activity> selected = new List<Activity>();
int lastEnd = 0;
foreach (var activity in activities) {
if (activity.StartTime >= lastEnd) {
selected.Add(activity);
lastEnd = activity.EndTime;
}
}
return selected;
}Sorting activities by their end time ascending uses subtraction (a.EndTime - b.EndTime) for correct order.
Fill both blanks to implement bottom-up dynamic programming for the coin change problem.
int CoinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
for (int i = 1; i <= amount; i++) {
dp[i] = amount + 1;
for (int j = 0; j < coins.Length; j++) {
if (coins[j] <= i) {
dp[i] = Math.Min(dp[i], dp[i [1] coins[j]] [2] 1);
}
}
}
return dp[amount] > amount ? -1 : dp[amount];
}We subtract coin value from i to get previous state and add 1 coin to count.
Fill all three blanks to implement recursive solution with memoization for the knapsack problem.
int Knapsack(int[] weights, int[] values, int capacity, int index, Dictionary<(int, int), int> memo) {
if (index == weights.Length || capacity == 0) return 0;
if (memo.ContainsKey((index, capacity))) return memo[(index, capacity)];
int skip = Knapsack(weights, values, capacity, index [1] 1, memo);
int take = 0;
if (weights[index] <= capacity) {
take = values[index] + Knapsack(weights, values, capacity [2] weights[index], index [3] 1, memo);
}
memo[(index, capacity)] = Math.Max(skip, take);
return memo[(index, capacity)];
}We move to next index by adding 1, and reduce capacity by subtracting weight.
