【发布时间】:2019-10-27 15:16:20
【问题描述】:
我正在尝试通过记忆来解决“计数变化”问题。
考虑以下问题:给定 1.00 美元、25 美分、10 美分、5 美分和便士,我们可以用多少种不同的方式找零?更一般地说,我们可以编写一个函数来计算使用任何一组货币面额来改变任何给定金额的方法的数量吗?
以及使用递归的直观解决方案。
用n种硬币改变a数量的方法数等于
- 使用除第一种硬币以外的所有硬币换硬币的方法数,加上
- 使用所有 n 种硬币更改较小金额 a - d 的方法数,其中 d 是第一种硬币的面额。
#+BEGIN_SRC python :results output
# cache = {} # add cache
def count_change(a, kinds=(50, 25, 10, 5, 1)):
"""Return the number of ways to change amount a using coin kinds."""
if a == 0:
return 1
if a < 0 or len(kinds) == 0:
return 0
d = kinds[0] # d for digit
return count_change(a, kinds[1:]) + count_change(a - d, kinds)
print(count_change(100))
#+END_SRC
#+RESULTS:
: 292
我尝试利用记忆,
Signature: count_change(a, kinds=(50, 25, 10, 5, 1))
Source:
def count_change(a, kinds=(50, 25, 10, 5, 1)):
"""Return the number of ways to change amount a using coin kinds."""
if a == 0:
return 1
if a < 0 or len(kinds) == 0:
return 0
d = kinds[0]
cache[a] = count_change(a, kinds[1:]) + count_change(a - d, kinds)
return cache[a]
它适用于像
这样的小数字In [17]: count_change(120)
Out[17]: 494
处理大数据
In [18]: count_change(11000)
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-18-52ba30c71509> in <module>
----> 1 count_change(11000)
/tmp/ipython_edit_h0rppahk/ipython_edit_uxh2u429.py in count_change(a, kinds)
9 return 0
10 d = kinds[0]
---> 11 cache[a] = count_change(a, kinds[1:]) + count_change(a - d, kinds)
12 return cache[a]
... last 1 frames repeated, from the frame below ...
/tmp/ipython_edit_h0rppahk/ipython_edit_uxh2u429.py in count_change(a, kinds)
9 return 0
10 d = kinds[0]
---> 11 cache[a] = count_change(a, kinds[1:]) + count_change(a - d, kinds)
12 return cache[a]
RecursionError: maximum recursion depth exceeded in comparison
记忆解法有什么问题?
【问题讨论】:
-
努力!但很少有问题,请检查stackoverflow.com/questions/1988804/…
标签: python-3.x algorithm coin-change