动态规划 零钱兑换 II

参考书目:《程序员代码面试指南:IT名企算法与数据结构题目最优解》

给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。假设每一种面额的硬币有无限个。

示例 1:

输入: amount = 5, coins = [1, 2, 5]

输出: 4

解释: 有四种方式可以凑成总金额:

5=5

5=2+2+1

5=2+1+1+1

5=1+1+1+1+1

示例 2:

输入: amount = 3, coins = [2]

输出: 0

解释: 只用面额2的硬币不能凑成总金额3。

示例 3:

输入: amount = 10, coins = [10]

输出: 1

注意:

你可以假设:

0 <= amount (总金额) <= 5000

1 <= coin (硬币面额) <= 5000

硬币种类不超过 500 种

结果符合 32 位符号整数

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/coin-change-2

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1. 暴力递归

class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
return self.process(coins, 0, amount) def process(self, coins, index, amount):
res = 0
if index == len(coins):
return 1 if amount == 0 else 0
else:
i = 0
while coins[index] * i <= amount:
res += self.process(coins, index+1, amount - i*coins[index])
i += 1
return res

暴力递归方法的时间复杂度非常高,并且与 arr 中钱的面值有关,最差情况下为O(amountN

2. 记忆化搜索

# 用-1标记是否计算过
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
coin_num = len(coins)
counts = [[0 for i in range(amount+1)] for j in range(coin_num+1)]
return self.process(coins, 0, amount, counts) def process(self, coins, index, amount, counts):
res = 0
if index == len(coins):
return 1 if amount == 0 else 0
else:
i = 0
while coins[index]*i <= amount:
value = counts[index+1][amount-coins[index]*i]
if value != 0:
res += 0 if value == -1 else value
else:
res += self.process(coins, index+1, amount-coins[index]*i, counts)
i += 1
counts[index][amount] = -1 if res == 0 else res
return res

记忆化搜索方法的时间复杂度为 O(N×amount2)

# 超时代码;未标记是否计算过。
class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
coin_num = len(coins)
counts = [[0 for i in range(amount+1)] for j in range(coin_num+1)]
return self.process(coins, 0, amount, counts) def process(self, coins, index, amount, counts):
res = 0
if index == len(coins):
return 1 if amount == 0 else 0
else:
i = 0
while coins[index]*i <= amount:
value = counts[index+1][amount-coins[index]*i]
if value != 0:
res += value
else:
res += self.process(coins, index+1, amount-coins[index]*i, counts)
i += 1
counts[index][amount] = res
return res

3. 动态规划方法

时间复杂度为 O(N×amount2

class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
return self.process(coins, amount) def process(self, coins, amount):
counts = [[0 for i in range(amount+1)] for j in range(len(coins)+1)]
for i in range(len(coins)):
counts[i][0] = 1
j = 0
while coins[0]*j <= amount:
counts[0][coins[0]*j] = 1
j += 1
for i in range(1, len(coins)):
for j in range(1, amount+1):
num = 0
k = 0
while coins[i]*k <= j:
num += counts[i-1][j-coins[i]*k]
k += 1
counts[i][j] = num
return counts[len(coins)-1][amount]

记忆化搜索的方法说白了就是不关心到达某一个递归过程的路径,只是单纯地对计算过的递归过程进行记录,避免重复的递归过程,而动态规划的方法则是规定好每一个递归过程的计算顺序,依次进行计算,后计算的过程严格依赖前面计算过的过程。

4. 进一步优化的动态规划算法

时间复杂度O(N×amount)

class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
return self.process(coins, amount) def process(self, coins, amount):
counts = [[0 for i in range(amount+1)] for j in range(len(coins)+1)]
for i in range(len(coins)):
counts[i][0] = 1
j = 0
while coins[0]*j <= amount:
counts[0][coins[0]*j] = 1
j += 1
for i in range(1, len(coins)):
for j in range(1, amount+1):
counts[i][j] = counts[i-1][j]
counts[i][j] += counts[i][j-coins[i]] if j - coins[i] >= 0 else 0 # 简化为dp[i][j]=dp[i-1][j]+dp[i][j-arr[i]]。一下省去了枚举的过程,时间复杂度也减小至O(N×amount)
return counts[len(coins)-1][amount]

5. 对空间进一步优化

class Solution(object):
def change(self, amount, coins):
"""
:type amount: int
:type coins: List[int]
:rtype: int
"""
if amount == 0:
return 1
if not coins or amount < 0:
return 0
return self.process(coins, amount) def process(self, coins, amount):
counts = [0 for i in range(amount+1)]
j = 0
while coins[0]*j <= amount:
counts[coins[0]*j] = 1
j += 1
for i in range(1, len(coins)):
for j in range(1, amount+1):
counts[j] += counts[j-coins[i]] if j - coins[i] >= 0 else 0 # 空间压缩
return counts[amount]

时间复杂度为O(N×aim)、额外空间复杂度O(aim)的方法。

动态规划——详解leetcode518 零钱兑换 II的更多相关文章

  1. [Swift]LeetCode518. 零钱兑换 II | Coin Change 2

    You are given coins of different denominations and a total amount of money. Write a function to comp ...

  2. 【LeetCode动态规划#08】完全背包问题实战与分析(零钱兑换II)

    零钱兑换II 力扣题目链接(opens new window) 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 示例 1: 输入: amoun ...

  3. Leetcode 518.零钱兑换II

    零钱兑换II 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 注意: 你可以假设 0 <= amount (总金额) <= 500 ...

  4. Java实现 LeetCode 518 零钱兑换 II

    518. 零钱兑换 II 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 示例 1: 输入: amount = 5, coins = [1, ...

  5. 刷题-力扣-518. 零钱兑换 II

    518. 零钱兑换 II 题目链接 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/coin-change-2/ 著作权归领扣网络所有.商业转载 ...

  6. TSP(旅行者问题)——动态规划详解(转)

    1.问题定义 TSP问题(旅行商问题)是指旅行家要旅行n个城市,要求各个城市经历且仅经历一次然后回到出发城市,并要求所走的路程最短. 假设现在有四个城市,0,1,2,3,他们之间的代价如图一,可以存成 ...

  7. leetcode-53-Maximum Subarray(动态规划详解)

    题目描述: Given an integer array nums, find the contiguous subarray (containing at least one number) whi ...

  8. HDU 1024 Max Sum Plus Plus【动态规划求最大M子段和详解 】

    Max Sum Plus Plus Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  9. 详解动态规划(Dynamic Programming)& 背包问题

    详解动态规划(Dynamic Programming)& 背包问题 引入 有序号为1~n这n项工作,每项工作在Si时间开始,在Ti时间结束.对于每项工作都可以选择参加与否.如果选择了参与,那么 ...

  10. (转)dp动态规划分类详解

    dp动态规划分类详解 转自:http://blog.csdn.NET/cc_again/article/details/25866971 动态规划一直是ACM竞赛中的重点,同时又是难点,因为该算法时间 ...

随机推荐

  1. PLSQL 无法查询带中文的WHERE条件

    今天遇到一个坑爹的问题,plsql无法查询带where条件的语句,是因为plsql中Oracle的客户端字符集和服务器上的不一样造成的,需要新增系统环境变量,特意记录下解决办法. 第一步:查询服务器上 ...

  2. yb课堂实战之首页banner轮播图和视频详情接口开发 《四》

    开发轮播列表接口 VideoMapper.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCT ...

  3. PLSQL 编码设置

    1.先查询plsql编码格式 select userenv('language')from dual 2.新建用户变量,变量名=NLS_LANG,变量值,刚才sql查询的结果 保存后,重启plsql即 ...

  4. 网易数帆开源贡献获业界肯定,轻舟API网关获OSCAR尖峰开源技术创新奖

    2020年10月16日,由中国信息通信研究院主办的"2020开源产业大会"在北京线下与线上同步召开,主办方在会上公布了"OSCAR尖峰开源奖项"各个奖项的评选结 ...

  5. 高程读后感(四)— 关于BOM本人容易忽略的知识点总结

    目录 window对象 window对象上属性及方法 超时调用setTimeout和间歇调用setInterval BOM location对象及其位置操作 history对象 window对象 wi ...

  6. 利用FastAPI和OpenAI-Whisper打造高效的语音转录服务

    最近好久没有写博客了,浅浅记录下如何将OpenAI-Whisper做成Web服务吧 介绍 在这篇指导性博客中,我们将探讨如何在Python中结合使用FastAPI和OpenAI-Whisper.Ope ...

  7. [oeasy]python0051_ 转义_escape_字符_character_单引号_双引号_反引号_ 退格键

    转义字符 回忆上次内容 上次研究的是进制转化 10进制可以转化为其他形式 bin oct hex 其他进制也可以转化为10进制 int 可以设置base来决定转为多少进制 回忆一下 我们为什么会有八进 ...

  8. [oeasy]教您玩转linux0001 - 先跑起来 🥊

    Python 什么是 Python? Python 很好用 适合初学者 而且在各个领域都很强大   ​   添加图片注释,不超过 140 字(可选)   后来居上 下图可以点开   ​   添加图片注 ...

  9. 【楔子】单细胞测序-最佳的分析Pipeline

    作者:starlitnightly 日期:2023.07.14 !!! note 楔子 从事单细胞分析也有一段时间了,国内大部分中文教程都是使用R语言进行分析,使用Python的还比较少,或者是直译s ...

  10. XXL-JOB分片执行分布式任务

    XXL-JOB相对于springtask来说优点之一就是分布式执行任务,可以在调度中心为执行器分发任务,实现分布式. 分片广播任务即当一个微服务形成集群的时候,任务会完整的下发给每一个执行器.而不像其 ...