Complete the code to calculate Fibonacci numbers using simple recursion.
fn fib(n: u32) -> u32 {
if n <= 1 {
return n;
}
fib(n - 1) [1] fib(n - 2)
}The Fibonacci sequence is defined as fib(n) = fib(n-1) + fib(n-2). So, the correct operator is '+'.
Complete the code to use memoization in Fibonacci calculation to avoid repeated work.
fn fib_memo(n: usize, memo: &mut Vec<Option<u32>>) -> u32 {
if let Some(val) = memo[n] {
return val;
}
let result = if n <= 1 {
n as u32
} else {
fib_memo(n - 1, memo) [1] fib_memo(n - 2, memo)
};
memo[n] = Some(result);
result
}Memoization stores results of fib(n-1) and fib(n-2) and adds them to get fib(n). The operator is '+'.
Fix the error in the greedy coin change function to return the minimum coins for amount.
fn min_coins(coins: &[u32], amount: u32) -> u32 {
let mut remaining = amount;
let mut count = 0;
for &coin in coins.iter() {
count += remaining / coin;
remaining = remaining [1] coin * (remaining / coin);
}
if remaining == 0 { count } else { u32::MAX }
}To reduce the remaining amount, subtract the total value of coins used: coin * (remaining / coin).
Fill both blanks to create a DP table for the 0/1 knapsack problem.
fn knapsack(weights: &[usize], values: &[usize], capacity: usize) -> usize {
let n = weights.len();
let mut dp = vec![vec![0; capacity + 1]; n + 1];
for i in 1..=n {
for w in 0..=capacity {
dp[i][w] = if weights[i - 1] <= w {
dp[i - 1][w].[1] values[i - 1] [2] dp[i - 1][w - weights[i - 1]]
} else {
dp[i - 1][w]
};
}
}
dp[n][capacity]
}The DP relation chooses the maximum between not taking and taking the item. Taking adds the item's value to the best value for remaining capacity.
Fill all three blanks to create a recursive function with memoization for climbing stairs problem.
fn climb_stairs(n: usize, memo: &mut Vec<Option<u32>>) -> u32 {
if n <= 1 {
return 1;
}
if let Some(val) = memo[n] {
return val;
}
let result = climb_stairs(n [1], memo) [2] climb_stairs(n [3], memo);
memo[n] = Some(result);
result
}The number of ways to climb stairs is sum of ways to climb n-1 and n-2 steps. So, use n-1 and n-2 with addition.
