在我看来,代码正在解决问题,每个分值直到目标分值.给定目标值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]