Python 给定数量的每枚硬币拆卸和组合的数量

Python 给定数量的每枚硬币拆卸和组合的数量,python,algorithm,Python,Algorithm,我看到过一些类似的问题,但没有掌握其中的诀窍。基本上,我有以下输入: coins [1,2,3] amount 4 有多少种方法可以给我这个数目?因此,上述情况将是: 1, 1, 1, 1 2,2 1,1,2 3,1 到目前为止,我的方法是循环硬币并在每个循环上切片图标集合,从而减少需要使用的硬币的大小。但我无法付诸行动。这是我到目前为止所做的尝试,它只为硬币(如1,1,1,1或2,2)提供正确的输出 我的问题是循环“下一组”硬币,看看它们

我看到过一些类似的问题,但没有掌握其中的诀窍。基本上,我有以下输入:

   coins [1,2,3]
   amount 4
有多少种方法可以给我这个数目?因此,上述情况将是:

     1, 1, 1, 1
     2,2
     1,1,2
     3,1
到目前为止,我的方法是循环硬币并在每个循环上切片图标集合,从而减少需要使用的硬币的大小。但我无法付诸行动。这是我到目前为止所做的尝试,它只为硬币(如1,1,1,1或2,2)提供正确的输出

我的问题是循环“下一组”硬币,看看它们的组合是否能合理地提供所需的数量

def cal2(amount, coins):
    result = {}
    def act(amount, coins):
        if amount == 0 or len(coins) == 0:
            return {}

        else:
            while (len(coins)>0):
                firstCoin = coins[0]

                if amount % firstCoin == 0 and not firstCoin in result.keys():

                    parts = amount // firstCoin
                    if not firstCoin in result.keys():
                        result[firstCoin] = parts



                if len(coins)>1:
                    # we still have coins to test....
                    nextCoin = coins[1]

                # remove current coin from the collection

                coins = coins[1:]

    act(amount,coins)
    return result
因此:

您可以使用递归:

coins = [1,2,3]
amount = 4
def combinations(d, _to, current):
  if sum(current) == _to:
    yield sorted(current)
  else:
    for i in d:
     if sum(current+[i]) <= _to:
        yield from combinations(d, _to, current+[i])

r = list(combinations(coins, amount, []))
final_result = [a for i, a in enumerate(r) if a not in r[:i]]
coins = [1,2,3]
amount = 4
def combinations(d, _to, current):
  if sum(current) == _to:
    yield sorted(current)
  else:
    for i in d:
     if sum(current+[i]) <= _to:
        yield from combinations(d, _to, current+[i])

r = list(combinations(coins, amount, []))
final_result = [a for i, a in enumerate(r) if a not in r[:i]]
[[1, 1, 1, 1], [1, 1, 2], [1, 3], [2, 2]]