【问题标题】:Recursion Coin Change problem gives wrong answer递归硬币找零问题给出了错误的答案
【发布时间】:2021-08-06 01:42:50
【问题描述】:

为什么我的代码在硬币为 [1,2,3] 时在 4 次中打印出 7 次“找到解决方案”,美分的变化为 4。应该只有 4 个可能的解决方案。我在这里做错了什么?

def coinChange(nCents, coins, total):
    if (total == nCents):
        print("Found solution")
        return 
    if (total > nCents):
        return
    if (total < nCents):
        for i in range(len(coins)):
            coinChange(nCents, coins, total+coins[i])

coins = [1,2,3]

coinChange(4, coins, 0)

【问题讨论】:

  • 首先,您应该在找到每个解决方案时将其打印出来。其次,您可能会得到解决方案的排列:[3,1], [1,3], [2,2], [2,1,1],[1,2,1],[1,1,2],[1,1,1,1],因此您应该对解决方案进行排序,或者永远不要使用大于最后添加的硬币的硬币。
  • 对不起,我很困惑不应该添加的下一个硬币更大所以列表将被排序?
  • 你应该从最适合的硬币开始,然后往下走。

标签: python algorithm recursion


【解决方案1】:

为什么的直接答案可以通过跟踪您使用的硬币并将结果打印出来来找到。这将清楚为什么您会得到七个结果:

def coinChange(nCents, coins, total, coin_list = None):
    if coin_list is None:
        coin_list = []
    if (total == nCents):
        print("Found solution", coin_list)
        return 
    if (total > nCents):
        return
    if (total < nCents):
        for i in range(len(coins)):
            coinChange(nCents, coins, total+coins[i], coin_list + [coins[i]])

coins = [1,2,3]

coinChange(4, coins, 0)

打印出来:

Found solution [1, 1, 1, 1]
Found solution [1, 1, 2]
Found solution [1, 2, 1]
Found solution [1, 3]
Found solution [2, 1, 1]
Found solution [2, 2]
Found solution [3, 1]

如您所见,这得到了这个结果,因为它认为像 [1, 1, 2] [1, 2, 1][2, 1, 1] 这样的解决方案是不同的。

【讨论】:

  • 非常感谢,避免重复结果但每次选择仍然有无限硬币的最佳方法是什么?
  • 你可以将一个切片传回递归:coinChange(nCents, coins[i:], total+coins[i], coin_list + [coins[i]]) 理解为什么这样工作不是很明显,但很有趣。
  • @sam202252012 是的(以及[1, 1, 2][2, 2]),但你不应该相信我的话……试试吧。
  • 正是@sam202252012!它会一直这样做,直到遇到其他门之一——它要么等于目标,要么变得太大。
  • 非常感谢马克,这真的帮助了我。此外,即使您对数组进行切片,每个组合的第一个变体仍然可以正常运行,因此为什么会起作用?
【解决方案2】:

这不是对采购订单的直接答复。但它宁愿展示另一种方式 - 动态编程方式来解决同样的问题:

def coin_ways(coins, amount):
    dp = [[] for _ in range(amount+1)]
    
    dp[0].append([])      # or table[0] = [[]], if prefer

    for coin in coins:
        for x in range(coin, amount+1):
            dp[x].extend(ans + [coin] for ans in dp[x-coin])
    #print(dp)
    
    return dp[amount]


if __name__ == '__main__':
    coins = [1, 2, 3]  # 
 
    print(coin_ways(coins, 4))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多