defchange(num):
lst =[25,10,5,1]
dic ={
25:0,10:0,5:0,1:0}
pos =0while num >= lst[pos]:
dic[lst[pos]]+=1#硬币数量加一
num -= lst[pos]#找零金额更新while num < lst[pos]and num !=0:
pos +=1return dic
change(63)
2. 低效递归找零(贪心策略失效)
defchange(coinlst,value):
mincoins = value
if value in coinlst:return1else:for i in[each for each in coinlst if each<=value]:
numcoins =1+ change(coinlst,value-i)if numcoins < mincoins:
mincoins = numcoins
return mincoins
print(change([25,10,5,1],63))#需要很久才能得到这个结果--6
3. 高效递归找零(贪心策略失效)
defchange(coinlst,value,dic ={
}):
mincoins = value
if value in coinlst:return1elif value in dic:return dic[value]#若记录的金额重复出现,则不再递归,而是直接返回值else:for i in[each for each in coinlst if each<=value]:
numcoins =1+ change(coinlst,value-i)if numcoins < mincoins:
mincoins = numcoins
dic[value]= mincoins #记录找零最小硬币数return mincoins
print(change([25,10,5,1],63))
4. 动态规划找零(得到找零硬币数目)
defchange(coinlst,value,mincoins):for i inrange(1,value+1):#初始化一个最大值
mincoins[i]= i
for j in[each for each in coinlst if each <= i]:
numcoins =1+ mincoins[i-j]if numcoins < mincoins[i]:
mincoins[i]= numcoins
return mincoins[value]print(change([1,5,10,21,25],63,[0]*64))
5. 动态规划找零(得到各面值硬币个数)
defchange(coinlst,value,mincoins,newcoin):for i in