python 最小硬币数_python – 动态规划最优硬币变化

在我看来,代码正在解决问题,每个分值直到目标分值.给定目标值v和一组硬币C,您知道最佳硬币选择S必须是联合形式(S’,c),其中c是来自C的一些硬币,S’是v的最佳解决方案 – 值(c)(借口我的记号).所以问题有

optimal substructure.动态编程方法是解决每个可能的子问题.这需要几美分(C)步骤,而不是如果你只是试图强制直接解决方案那么爆炸得更快.

def dpMakeChange(coinValueList,change,minCoins):

# Solve the problem for each number of cents less than the target

for cents in range(change+1):

# At worst, it takes all pennies, so make that the base solution

coinCount = cents

# Try all coin values less than the current number of cents

for j in [c for c in coinValueList if c <= cents]:

# See if a solution to current number of cents minus the value

# of the current coin, with one more coin added is the best

# solution so far

if minCoins[cents-j] + 1 < coinCount:

coinCount = minCoins[cents-j]+1

# Memoize the solution for the current number of cents

minCoins[cents] = coinCount

# By the time we're here, we've built the solution to the overall problem,

# so return it

return minCoins[change]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值