leetcode-322

132 阅读1分钟

题目描述:具体描述见原题。简单来说就是使用最少数量的钱币凑够目标值,钱币数额范围给定,且每一枚钱币可以重复使用。

解题思路:这道题集体思路和NO.279几乎一样。具体过程见代码。

具体代码:

func coinChange(coins []int, amount int) int {
    if len(coins) == 0 || amount == 0 {
		return 0
	}
	res := make([]int, amount+1)
	res[0] = 0 // res[0]初始化为0
	for i := 1; i < len(res); i++ {
		res[i] = amount+1 // 初始化res,每项也可以初始化为math.max
	}
	for i := 1; i < len(res); i++ {
		for _, c := range coins{
			if c <= i {
				res[i] = min(res[i], res[i-c]+1) // 每引入一枚新额度钱币,更新res值
			}
		}
	}
	if res[amount] > amount {
		return -1
	}
	return res[amount]
}

func min(x, y int) int {
    if x < y {
        return x
    }
    return y
}

补充说明:下午继续划水修改论文。