python-3.x - 用有限的硬币找零
问题描述
import sys
def minCoins(coins, m, how, V):
# table[i] will be storing the minimum
# number of coins required for i value.
# So table[V] will have result
table = [0 for i in range(V + 1)]
index = []
# Base case (If given value V is 0)
table[0] = 0
# Initialize all table values as Infinite
for i in range(1, V + 1):
table[i] = sys.maxsize
# Compute minimum coins required
# for all values from 1 to V
for i in range(1, V + 1):
# Go through all coins smaller than i
for j in range(m):
if (coins[j] <= i):
sub_res = table[i - coins[j]]
if (sub_res != sys.maxsize and
sub_res + 1 < table[i]):
if sub_res +1 <= how[j] :
table[i] = sub_res + 1
return table[V]
coins = [200, 100, 50, 20, 10, 5, 2, 1]
howmanycoins = [0, 2, 2, 3, 0, 0, 7, 8]
m = len(coins)
V = 16
print("Minimum coins required is ", minCoins(coins, m, howmanycoins, V))
我对这段代码有疑问。当 tablehowmanycoins
有这个值时,[0, 2, 2, 3, 0, 0, 7, 9]
程序给出很好的答案 7x "2" + 2x "1" = 9 个硬币,但是当 8 在最后一个位置时,输出如下所示:
所需的最低硬币为 9223372036854775807。
解决方案
看这行代码:
if sub_res +1 <= how[j] :
在这里你检查你没有使用更多的硬币how[j]
,但实际上这些sub_res + 1
硬币可以有不同的价值,而不仅仅是coins[j]
价值。最小的例子:
coins = [1, 2]
howmanycoins = [1, 1]
m = len(coins)
V = 3
行不通,因为您显然需要 2 个硬币,但是2 > how[0]
and 2 > how[1]
, 但在这种情况下,您使用每个值的 1 个硬币。
为了解决您的问题,您应该为每个值保存所有使用过的硬币,并将您的算法更改为蛮力。
推荐阅读
- scheme - how to handle this error generated in doing sicp exercise 4.9?
- php - 获取保存在 MySQL 数据库中的 blob 类型 PDF
- javascript - 如何提取通过 multipart/form-data 发送的文件的 Content-Type
- python - how to group by and sort the columns given the column value in a function
- java - 类 VS 对象 VS 实例
- php - 如何处理来自共享相同值的多个复选框的数据?
- android - 如何解决 Recycler View Adapter 上的 Android 运行时异常?
- r - Variable Importance for caret loclda method
- ios - How to fetch only image assets from smart albums with NSPredicate in Swift 4.2?
- db2 - 我如何识别缓冲池中可用的数据以及该数据与哪些事务相关?