零钱兑换
周二打卡,这道题本来是周一做的,太难了,没做出来,拖到今天来打卡。懵逼脸~我尽量用人话描述清楚。
题目描述
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
来源:力扣(LeetCode)
原题链接:https://leetcode-cn.com/problems/coin-change
解题思路
- 先列出我们已经知道的条件,不同面值的硬币(数组,没有规定具体有几种硬币),切硬币的量没有上限值。总金额amount,是固定值。
- 当总金额为0时有0种可能,当没有组合可以组成总金额时返回-1。
- 将条件写成函数,令所求的最优解为N,既有N = f(amount),如果满足条件的最后一枚硬币的面值为coin, 则有, N=f(amount -coin)+ 1
- 上述所列则为递推公式,再设置递归出口,则可以写出暴力破解算法
初始1.0版
class Solution(object):
def coinChange(self, coins, amount):
def dp(n):
if n == 0: return 0
if n < 0: return -1
res = float('INF')
for coin in coins:
subproblem = dp(n - coin)
if subproblem == -1: continue
res = min(res, 1 + subproblem)
return res
return dp(amount)
图解和优化
将 coins = [1, 2, 5], amount = 11模拟,即如图
优化:可以看出时间复杂度为指数级别,同时存在大量重复计算,可以用字典存储计算结果,避免重复计算。
带字典的动态规划
class Solution(object):
def coinChange(self, coins, amount):
dic = dict()
def dp(n):
if n in dic: return dic[n]
if n == 0: return 0
if n < 0: return -1
res = float('INF')
for coin in coins:
subproblem = dp(n - coin)
if subproblem == -1: continue
res = min(res, 1 + subproblem)
dic[n] = res if res != float('INF') else -1
return dic[n]
return dp(amount)
时间复杂度为 O(kn)
循环表现形式
可以将递归改写成循环形式,代码如下
class Solution(object):
def coinChange(self, coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
小结
代码贴在这里给大家做个参考,其实我感觉我也还没有完全理解,多做做动态规划的题可能就好了。每日一句,与君共勉。
尽管好几十万人聚居在一小块地方,竭力把土地糟蹋得面目全非,尽管他们肆意把石头砸进地里,不让花草树木生长。尽管刚出土的小草被清除,尽管煤炭和石油燃烧的浓烟四处弥漫,尽管树木被滥伐,鸟兽被驱逐,即使在这样的城市里,春天仍然是春天。
Though hundreds of thousands had done their very best to disfigure the small piece of land on which they were crowded together, by paying the ground with stones, scraping away every vestige of vegetation, cutting down the trees, turning away birds and beasts, and filling the air with the smoke of naphtha and coal, still spring was spring, even in the town.
————列夫托尔斯泰《复活》