博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 332, Coin Change
阅读量:4576 次
发布时间:2019-06-08

本文共 1097 字,大约阅读时间需要 3 分钟。

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

Example 1:

coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)

Example 2:

coins = [2], amount = 3
return -1.

Note:

You may assume that you have an infinite number of each kind of coin.

 

本题不能用greedy algorithm。因为硬币的组合可能不是greedy basis。离散的问题求极值一般还是使用DP。

 

1 class Solution(object): 2     def coinChange(self, coins, amount): 3         """ 4         :type coins: List[int] 5         :type amount: int 6         :rtype: int 7         """ 8         int_max = 2147483647 9         dp = [0]+[int_max]*amount10         11         for i in range(amount+1):12             for coin in coins:13                 if coin <= i:14                     dp[i] = min(dp[i],dp[i-coin]+1)15         16         if dp[amount] < int_max:17             return dp[amount]18         else:19             return -1

 

转载于:https://www.cnblogs.com/lettuan/p/6104349.html

你可能感兴趣的文章
边工作边刷题:70天一遍leetcode: day 45
查看>>
淘宝专业版改基础版方法
查看>>
[转]ARM Pipeline
查看>>
[转]Blocking Code Injection on iOS and OS X
查看>>
自动化测试
查看>>
vue $options 获取自定义属性
查看>>
Vue避免 v-if 和 v-for 用在一起
查看>>
iview3 版本 升级
查看>>
EditTest 属性大全[便自己查阅]
查看>>
Webform 服务器控件与客户端控件以及验证控件
查看>>
TraceSource记录程序日志
查看>>
【Source教程】GCFScape下载安装与使用
查看>>
数据结构 单链表反转 回顾练习
查看>>
N!分解素因子及若干问题
查看>>
主动对象
查看>>
C++ string int 转换 split
查看>>
网站繁简切换的JS遇到的一个BUG
查看>>
Docker容器技术
查看>>
五秒后页面自动跳转
查看>>
Spark消息通信原理(三)——Spark运行时消息通信
查看>>