题目:
题解:
func coinChange(coins []int, amount int) int {
var (
dfs func(x int) int // x金额 最少硬币个数
memo = make(map[int]int) // 记忆化
)
dfs = func(x int) int {
//边界
if x == 0 {
return 0
} else if x < 0 {
return math.MaxInt32
}
//记忆化
if _, ok := memo[x]; ok {
return memo[x]
}
//状态转移
var res = math.MaxInt32
for _, y := range coins {
res = min(res, 1+dfs(x-y))
}
memo[x] = res
return res
}
ans := dfs(amount)
if ans == math.MaxInt32 {
return -1
}
return ans
}