Complete the code to calculate Fibonacci numbers using simple recursion.
func fib(n int) int {
if n <= 1 {
return n
}
return fib(n-1) [1] fib(n-2)
}The Fibonacci sequence is calculated by adding the two previous numbers, so the operator must be '+'.
Complete the code to add memoization to the Fibonacci function to avoid repeated calculations.
var memo = make(map[int]int)
func fibMemo(n int) int {
if n <= 1 {
return n
}
if val, ok := memo[n]; ok {
return val
}
memo[n] = fibMemo(n-1) [1] fibMemo(n-2)
return memo[n]
}Memoization stores results of fib(n) to avoid recomputation. The addition operator '+' is used to sum the two previous Fibonacci numbers.
Fix the error in the recursive factorial function to prevent infinite recursion.
func factorial(n int) int {
if n == 0 {
return 1
}
return n * factorial([1])
}The factorial function multiplies n by factorial of n-1. Using n-1 moves towards the base case and prevents infinite recursion.
Fill both blanks to complete the code that uses dynamic programming to find the minimum cost path in a grid.
func minCost(cost [][]int, m int, n int) int {
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}
dp[0][0] = cost[0][0]
for i := 1; i <= m; i++ {
dp[i][0] = dp[i-1][0] [1] cost[i][0]
}
for j := 1; j <= n; j++ {
dp[0][j] = dp[0][j-1] [2] cost[0][j]
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + cost[i][j]
}
}
return dp[m][n]
}To accumulate the cost along the path, we add the current cell cost to the previous minimum cost. So '+' is used in both blanks.
Fill all three blanks to complete the code that builds a memoized recursive solution for the climbing stairs problem.
var memoClimb = make(map[int]int)
func climbStairs(n int) int {
if n <= 1 {
return 1
}
if val, ok := memoClimb[[1]]; ok {
return val
}
memoClimb[n] = climbStairs(n-1) [2] climbStairs([3])
return memoClimb[n]
}The memo map stores results for n, so the key is 'n'. The number of ways to climb stairs is sum of ways to climb n-1 and n-2 steps, so '+' and 'n-2' are used.
