【问题标题】:Recursive memoization solutio to solve "count changes"解决“计数变化”的递归记忆解决方案
【发布时间】:2019-10-27 15:16:20
【问题描述】:

我正在尝试通过记忆来解决“计数变化”问题。

考虑以下问题:给定 1.00 美元、25 美分、10 美分、5 美分和便士,我们可以用多少种不同的方式找零?更一般地说,我们可以编写一个函数来计算使用任何一组货币面额来改变任何给定金额的方法的数量吗?

以及使用递归的直观解决方案。

用n种硬币改变a数量的方法数等于

  1. 使用除第一种硬币以外的所有硬币换硬币的方法数,加上
  2. 使用所有 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

记忆解法有什么问题?

【问题讨论】:

标签: python-3.x algorithm coin-change


【解决方案1】:

在memoized版本中,count_change函数必须考虑到递归调用时可以使用的coin的最高索引,这样你就可以使用已经计算的值...

def count_change(n, k, kinds):
    if n < 0:
        return 0
    if (n, k) in cache:
        return cache[n,k]
    if k == 0:
        v = 1
    else:
        v = count_change(n-kinds[k], k, kinds) + count_change(n, k-1, kinds)
    cache[n,k] = v
    return v

你可以试试:

cache = {}
count_change(120,4, [1, 5, 10, 25, 50])

给出 494

同时:

cache = {}
count_change(11000,4, [1, 5, 10, 25, 50])

输出:9930221951

【讨论】:

    猜你喜欢
    • 2018-10-07
    • 2020-08-09
    • 2021-06-23
    • 2022-01-19
    • 2021-02-17
    • 1970-01-01
    • 2013-07-22
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多