动态规划 零钱兑换 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. SpringBoot整合模版引擎freemarker实战

    Freemarker相关maven依赖 <dependency> <groupId>org.springframework.boot</groupId> <a ...

  2. 硬核案例分享,一文带你拆解PHP语言体系下的容器化改造

    本文分享自华为云社区<PHP语言体系下的容器化改造,助力夺冠集团应用现代化>,作者: HuaweiCloudDeveloper. 1.摘要 本文主要介绍了PHP语言体系应用现代化改造上云的 ...

  3. [oeasy]python020在游戏中体验数值自由_勇闯地下城_终端文字游戏

    继续运行 回忆上次内容 上次使用shell环境中的命令 命令 作用 cd 改变文件夹 pwd 显示当前文件夹 ls 列出当前文件夹下的内容 最终 进入 目录 找到 游戏   如果git clone 根 ...

  4. [oeasy]python0081_[趣味拓展]ESC键进化历史_键盘演化过程_ANSI_控制序列_转义序列_CSI

    光标位置 回忆上次内容 上次了解了 新的转义模式 \033 逃逸控制字符 escape 这个字符 让字符串 退出标准输出流 进行控制信息的设置 可以设置 光标输出的位置       ​   添加图片注 ...

  5. CF1468N 题解

    洛谷链接&CF 链接 题目简述 共有 \(T\) 组数据,对于每组数据: 有三个桶,五种垃圾,每个桶有固定的容量. 前三种垃圾分别放入三种桶中,第四种垃圾可以放进 \(1,3\) 桶中,第五种 ...

  6. 题解:CF1957A Stickogon

    CF1957A Stickogon 题意 题意十分简单,给予你 \(n\) 个棍子,问这些棍子可以构成多少个正多边形. 思路 说是可以构成多少个正多边形,所以我们可以用边最少的正多边形等边三角形来计数 ...

  7. 嘿,我使用了mp的自连接+分页查询之后,再使用条件查询居然失效了。

    原因:我想通过自连接查询将一个表的两条数据放在一起,为此我重写了mp的分页查询 IPage<Indi> selectIndiShow(IPage<Indi> page, @Pa ...

  8. proxmox ve 部署双节点HA集群及glusterfs分布式文件系统

    分布式存储的作用 加入分布式存储的目的:主要是为了对数据进行保护避免因一台服务器磁盘的损坏,导致数据丢失不能正常使用.   参考文档:https://gowinder.work/post/proxmo ...

  9. 【Eclipse】入门使用

    Eclipse界面简单概述 第一次启动时,工作空间的选择 工作界面的介绍: 选项条 工具栏 工程浏览窗口 工程大纲窗口 控制台输出窗口 在窗口选项中悬浮放在Show View选项中可以查看所有的窗口 ...

  10. 决定了,今日起开始准备弃用京东JD

    估计京东是为了节约开支,然后开始大比例的把快递物流业务进行外包了,这直接导致服务质量的直线下滑,10多年前我选择弃用当当网而选择京东JD就是因为当时当地的当当网快递是用沈阳晚报的快递上门的,快递员连P ...