本文介绍了最小硬币变化问题 - 回溯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以最少的硬币数量解决硬币找零问题使用回溯法.

I'm trying to solve Coin change problem with minimum number of coinsusing backtracking method.

我实际上已经完成了,但我想添加一些选项,以按单位打印硬币数量,而不仅仅是总数.

I've actually done with it, but I want to add some option that print the number of coins by its unit not only total amount.

这是我下面的python代码.

this is my python codes below.

def minimum_coins(coin_list, change):
min_coins = change
if change in coin_list:
    return 1
else:
    for coin in coin_list:
        if coin < change:
            num_coins = 1 + minimum_coins(coin_list, change - coin)
            if num_coins < min_coins:
                min_coins = num_coins
return min_coins

coin_list = []
unit = input("Enter the Coin Unit\n")
#1 10 15 20
change = int(input("Enter the Total Change\n"))
#73
unit = unit.split()

for i in unit:
    coin_list.append(int(i))

min = minimum_coins(coin_list, change)
#print("You need 3 1's, 1 10's, 0 15's, 3 20's") <- I want to implement this option.
print("Total number of coins required is %s." % min) #7

我正在努力在我的代码中实现这一点.

I'm struggling to implement this in my code.

因为回溯很复杂,我不知道如何按单位检查硬币数量.

cause back-tracking is complex, I can't get the idea how to check the number of coins by its unit.

推荐答案

可能的方式:

def minimum_coins(coin_list, change):
    min_coins = change
    if change in coin_list:
        return 1, [change]
    else:
        cl = []
        for coin in coin_list:
            if coin < change:
                mt, t = minimum_coins(coin_list, change - coin)
                num_coins = 1 + mt
                if num_coins < min_coins:
                    min_coins = num_coins
                    cl = t + [coin]
    return min_coins, cl

change = 73
coin_list = [1, 10, 15, 20]
min, c = minimum_coins(coin_list, change)
#print("You need 3 1's, 1 10's, 0 15's, 3 20's") <- I want to implement this option.
print("Total number of coins required is %s." % min, c) #7

>>>Total number of coins required is 7. [20, 20, 20, 10, 1, 1, 1]

这篇关于最小硬币变化问题 - 回溯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-09 16:54