Skip to content

Latest commit

 

History

History
77 lines (55 loc) · 1.46 KB

0322.coin-change.md

File metadata and controls

77 lines (55 loc) · 1.46 KB
description
322. 零钱兑换

0322.Coin-Change

题目描述

题目地址

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。

你可以认为每种硬币的数量是无限的。

示例 1:

输入coins = [1, 2, 5], amount = 11
输出3 
解释11 = 5 + 5 + 1

题解

思路1 : 动态规划-自上而下

算法流程:

****

复杂度分析:

  • 时间复杂度$$O(N)$$
  • 空间复杂度$$O(N)$$

代码

{% tabs %} {% tab title="Go" %}

func coinChange(coins []int, amount int) int {
	dp := make([]int, amount+1)
	for i := 0; i < amount+1; i++ {
		dp[i] = amount + 1
	}
	dp[0] = 0

	for i := 1; i <= amount; i++ {
		for j := 0; j < len(coins); j++ {
			if coins[j] <= i {
				dp[i] = min(dp[i], dp[i-coins[j]]+1)
				
			}
		}
	}
	if dp[amount] > amount {
		return -1
	}
	return dp[amount]
}

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

{% endtab %} {% endtabs %}

总结

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 算法 题解:awesome-golang-algorithm