# 动态规划-最小硬币找零

最少硬币找零问题是硬币找零问题的一个变种。硬币找零问题是给出要找零的钱数，

// 最小硬币找零
function MinCoinChange(coins) {
var coins = coins; //{1}
var cache = {}; //{2}
this.makeChange = function (amount) {
var me = this;
console.log(amount,'amount')
if (!amount) { //{3}
return [];
}
if (cache[amount]) { //{4}
return cache[amount];
}
var min = [], newMin, newAmount;
for (var i = 0; i < coins.length; i++) { //{5}
var coin = coins[i];
newAmount = amount - coin; //{6}
if (newAmount >= 0) {
newMin = me.makeChange(newAmount); //{7}
console.log(newAmount, 'newAmount' , newMin, amount , 'amount')
}
if (
newAmount >= 0 && //{8}
(newMin.length < min.length - 1 || !min.length)//{9}
&& (newMin.length || !newAmount)) //{10} 判断newAmount是否有效，minValue （最少硬币数）是否是最优解，与此同时minValue和newAmount是否是合理的值
{
min = [coin].concat(newMin); //{11}
console.log('new Min ' + min + ' for ' + amount);
}
}
console.log(amount, min, 'cache')
return (cache[amount] = min); //{12}
};
}

codepen链接

https://codepen.io/pprachel/pen/NejOKK?editors=1111

posted @ 2018-12-24 17:08  宇晴  阅读(247)  评论(0编辑  收藏  举报