以下是针对最小硬币更换问题的强力解决方案。它需要一个int A,这是需要做出的改变,以及一系列硬币面额。它返回一个对象,结果,它具有可以根据硬币面额数组以及硬币数组返回的最小硬币。
例如,如果要求使用值10
对[1, 2, 5]
美分进行更改,则应返回2
硬币分钟和数组[0, 0, 2]
两分钱。< / p>
它返回正确的最小值但不是正确的硬币数组。
# values the algorithms should return, the min num of coins, the actual
# coins in an array, and the original
# array of coin denominations
class Results:
a = 0
change = []
coinsDenom = []
# A is an array of coin denominations
# C is the change to be made
# returns results object
def changeslow(A, C):
res = Results()
res.coinsDenom = C
res.change = []
# initialize your change array to be the length of the coindenom array
for i in range(0, len(res.coinsDenom)):
res.change.append(0)
minCoins = A
for i in [j for j in C if j <= A]:
if j == A:
res.a = 1
res.change[i] = res.change[i] + 1
return res
nextcall = changeslow(A-i, C)
numCoins = 1 + nextcall.a
if numCoins < minCoins:
minCoins = numCoins
res.change = nextcall.change
res.change[0] = res.change[0] + 1
res.a = minCoins
return res
答案 0 :(得分:0)
使用dynamic programming
可以最好地解决此问题。例如,请参阅此http://www.columbia.edu/~cs2035/courses/csor4231.F07/dynamic.pdf以获取以下直观的动态编程公式:
# DP-CHANGE
# find number of coins needed to represent a value and memoize the last coin
def DP_CHANGE(denoms, value):
num_coins = [0]*(value+1) # store number of coins needed to represent coin values from [0..value]
last_coin = [float('Inf')]*(value+1) # memoize last coin used to represent coin values from [0..value]
for d in denoms:
num_coins[d] = 1
for i in range(1, value + 1):
num_denom = min([(num_coins[i-d] + 1, d) for d in denoms if i - d >= 0])
num_coins[i], last_coin[i] = num_denom[0], num_denom[1]
return num_coins, last_coin
# TRACE-CHANGE
# back-trace the denominations used
def TRACE_CHANGE(value, last_coin):
denoms_used = []
while value > 0:
denoms_used.append(last_coin[value]);
value-=last_coin[value]
return denoms_used
def FIND_CHANGE(value, denoms):
num_coins, last_coin = DP_CHANGE(denoms, value)
print 'number of coins needed to represent values ' + str(range(value+1)) + ': ' + str(num_coins)
print 'minimum number of coins need to represent the value ' + str(value) + ': ' + str(num_coins[value])
print 'coins of denominations needed:' + str(TRACE_CHANGE(value, last_coin))
FIND_CHANGE(10, [1,2,5])
# number of coins needed to represent values [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
# [0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2]
# minimum number of coins need to represent the value 10: 2
# coins of denominations needed:[5, 5]