动态规划——详解leetcode518 零钱兑换 II
动态规划 零钱兑换 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的更多相关文章
- [Swift]LeetCode518. 零钱兑换 II | Coin Change 2
		
You are given coins of different denominations and a total amount of money. Write a function to comp ...
 - 【LeetCode动态规划#08】完全背包问题实战与分析(零钱兑换II)
		
零钱兑换II 力扣题目链接(opens new window) 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 示例 1: 输入: amoun ...
 - Leetcode 518.零钱兑换II
		
零钱兑换II 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 注意: 你可以假设 0 <= amount (总金额) <= 500 ...
 - Java实现 LeetCode 518 零钱兑换 II
		
518. 零钱兑换 II 给定不同面额的硬币和一个总金额.写出函数来计算可以凑成总金额的硬币组合数.假设每一种面额的硬币有无限个. 示例 1: 输入: amount = 5, coins = [1, ...
 - 刷题-力扣-518. 零钱兑换 II
		
518. 零钱兑换 II 题目链接 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/coin-change-2/ 著作权归领扣网络所有.商业转载 ...
 - TSP(旅行者问题)——动态规划详解(转)
		
1.问题定义 TSP问题(旅行商问题)是指旅行家要旅行n个城市,要求各个城市经历且仅经历一次然后回到出发城市,并要求所走的路程最短. 假设现在有四个城市,0,1,2,3,他们之间的代价如图一,可以存成 ...
 - leetcode-53-Maximum Subarray(动态规划详解)
		
题目描述: Given an integer array nums, find the contiguous subarray (containing at least one number) whi ...
 - 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 ...
 - 详解动态规划(Dynamic Programming)& 背包问题
		
详解动态规划(Dynamic Programming)& 背包问题 引入 有序号为1~n这n项工作,每项工作在Si时间开始,在Ti时间结束.对于每项工作都可以选择参加与否.如果选择了参与,那么 ...
 - (转)dp动态规划分类详解
		
dp动态规划分类详解 转自:http://blog.csdn.NET/cc_again/article/details/25866971 动态规划一直是ACM竞赛中的重点,同时又是难点,因为该算法时间 ...
 
随机推荐
- 通俗讲解promise
			
JavaScript 中的 Promise 是一种特殊的对象,它用于解决异步编程中的复杂性问题,特别是回调的问题.我们可以把它比喻成现实生活中的一个"承诺": 想象一下,你 ...
 - Django 结合Vue实现前端页面导出为PDF
			
Django结合Vue实现前端页面导出为PDF by:授客 QQ:1033553122 测试环境 Win 10 Python 3.5.4 Django-2.0.13.tar.gz 官方下载地址: ht ...
 - CF1915B Not Quite Latin Square 题解
			
CF1915B 题意 给出一个 \(3\) 行 \(3\) 列的字符矩形,其中每行都有字符 ABC 各一个组成,现有一个字符未知,求出未知字符. 思路 就是说每个字符都应该出现 \(3\) 次,所以我 ...
 - 关于使用UE5打包Android的测试
			
UE5打包Android,不同于UE4,在官方文档中需要Android studio 4.0或者3.5,还有Android SDK,NDK等 设置SetupAndroid, 在UE5 Editor配置 ...
 - LeetCode513. 找树左下角的值
			
题目链接:https://leetcode.cn/problems/find-bottom-left-tree-value/description/ 题目叙述: 给定一个二叉树的 根节点 root,请 ...
 - Diffutoon下载介绍:真人视频转动漫工具,轻松获得上千点赞
			
最近在刷短视频的时候,偶尔能看到一些真人转动漫风的作品,看起来给人一种新鲜感,流量都还不错,简简单单跳个舞,就能获得上千个点赞~ 那么,这种视频是怎么制作的? 本期给大家介绍一款AI转绘工具Diffu ...
 - 【Canal】01 入门 & Kafka模式
			
什么是Canal (卡耐尔) ? Canal 是用 Java 开发的基于数据库增量日志解析,提供增量数据订阅&消费的中间件 原理基于MySQL的binlog从库监听 一.MySQL ...
 - 【MySQL】JSON相关
			
一些概念 MySQL里的json分为json array和json object. $表示整个json对象,在索引数据时用下标(对于json array,从0开始)或键值(对于json object, ...
 - 【SpringBoot】11 Web开发 Part2 模板引擎
			
开发回顾: JavaWeb开发使用JSP技术,所有的页面文件必须是JSP,才能接受数据处理 JSP的好处是,数据交互方便,有JSTL补充 SpringBoot的区别: 我们最终的项目是一个jar包 内 ...
 - 【Shiro】02 shiro.ini文件分析
			
[什么是INI文件?] INI 全称:Initialization File 初始文件 Window系统文件扩展名 Shiro 使用时可以连接数据库,也可以不连接数据库. 当不使用数据库时,需要配置S ...