【发布时间】:2020-02-24 05:44:27
【问题描述】:
给定硬币面额列表和目标值,我正在尝试创建一个递归函数,该函数将告诉我产生该值所需的最小硬币数量,然后显示哪些硬币我' d 需要。例如输入硬币 [1,5,10,25] 和目标 6,输出应该是“你需要 2 个硬币:[1,5]” 我写了一个函数,告诉我需要多少硬币,但我也想看看硬币组合是什么。
# USD - $1, $5, $10, etc.
currency = [1, 5, 10, 20, 50, 100]
# the amount to change - eg $6
amount = 6
cache = dict()
def recursive_change(currency, amount):
if amount in cache.keys() is not None:
return cache[amount]
# base case
if amount == 0:
return 0
result = amount+1 # initially result is just some high number
#I figure amount + 1 is fine because we'd never use more coins than the value (assuming we can't have coins worth less than one)
for coin in currency:
if coin <= amount:
result = min(result, recursive_change(currency, amount-coin) + 1)
cache[amount]=result
return result
这是我刚刚制作的另一个版本 - 我注意到我最初的解决方案没有很好地处理不可能的输入(例如,只使用五分钱和一角硬币赚 6 美分),所以现在它返回 -1 表示不可能的金额。虽然它有点丑,但会喜欢一些关于让它变得更好的意见。
def recursive_change(currency, amount):
if amount in cache.keys():
return cache[amount]
# base case
if amount == 0:
return 0
# If we can't make the amount with this coin, return -1
if amount < 0:
return -1
result = -1
for coin in currency:
if coin <= amount:
current_result = recursive_change(currency, amount-coin)
if current_result >= 0:
if result < 0:
result = current_result
else:
result = min(current_result, result)
if result < 0:
result = -1
else:
result = result + 1
cache[amount]=result
print(cache)
return result
【问题讨论】:
-
@wim 感谢您的快速回复。我无法通过您提供的链接找到递归解决方案,我只看到迭代解决方案。
-
相关(DP方法)stackoverflow.com/a/41812422/674039。迭代代码更适合这个问题,你有什么理由想在这里使用递归?
-
我正在学习,我觉得我应该能够使用迭代和递归来解决问题。我想如果我能做到这一点,我会觉得我对递归的理解要好得多——而且这种模式可能对其他事情有用,比如如果我想递归地找到一条最短路径,我可以跟踪那条路径是什么,而不仅仅是知道如何很久了。