Dynamic programming
Dynamic programming solves a problem by storing answers to overlapping subproblems. In Go that is usually a slice or a map of memoized results, filled bottom-up or by a recursive function with a cache.
Detailed Explanation
A naive recursive Fibonacci branches into an exponential tree because fib(n-2) is recomputed from every fib(n-1). DP computes each fib(k) once and reuses it. The two ingredients are overlapping subproblems and optimal substructure (the best answer is built from best answers to smaller pieces).
Bottom-up tables. dp := make([]int, n+1) and a loop for i := 2; i <= n; i++ { dp[i] = ... }. This is the usual Go form: obvious lifetime, no recursion depth, easy to see O(n) space. You can often keep only the last two cells when the recurrence needs them.
Top-down memo. A recursive function plus memo map[key]int or a slice of optionals. Use a pointer to the map so recursive calls share it. Return a sentinel or a (value, ok) when you need to store a valid zero. Top-down only computes the states you need; bottom-up computes the whole table.
Keys in Go. An integer index is a slice. A pair (i, remaining) can be i*(W+1)+remaining into one slice, or a struct key in a map. Struct keys must be comparable — no slices inside the key. For grids, dp[i][j] as [][]int is clear; allocate rows with a loop or a single backing array.
What it costs. Time is (number of states) × (work per state). Space is the table, unless you compress it. A map memo is simpler to write and slower than a packed slice. Start with the clear table; compress when a memory limit or a profile says so.
Code Examples
package main
import "fmt"
func fib(n int) int {
if n < 2 {
return n
}
dp := make([]int, n+1)
dp[1] = 1
for i := 2; i <= n; i++ {
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n]
}
func main() {
fmt.Println(fib(10))
}func knapsack(w []int, val []int, cap int) int {
dp := make([]int, cap+1)
for i := range w {
for c := cap; c >= w[i]; c-- {
if v := dp[c-w[i]] + val[i]; v > dp[c] {
dp[c] = v
}
}
}
return dp[cap]
}func memoFib(n int, memo []int) int {
if n < 2 {
return n
}
if memo[n] != 0 || n == 0 {
return memo[n]
}
memo[n] = memoFib(n-1, memo) + memoFib(n-2, memo)
return memo[n]
}Common Gotchas
A memo that uses `0` as empty cannot store a real `0`
use a separate `[]bool` filled flag, or store `*int`.
Updating a 1D knapsack left-to-right reuses the same item
iterate capacity downward for 0/1 knapsack.
Map memos need comparable keys
flatten indexes when the key would contain a slice.
Recursion plus memo still uses stack
deep `n` should be bottom-up.