给定数量的每种硬币演示数量和组合数量

时间:2018-11-07 03:28:39

标签: 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这样的硬币给出正确的输出

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

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

所以:

      print(cal2(6, [1,2,3]))
      # gives 1:6, 2:3, 3:2 which just means two 3 coins can give 6...

1 个答案:

答案 0 :(得分:1)

您可以使用递归:

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]]