function MinCoinChange(coins) {
var coins = coins;
// cache存储了1到37的最优解
// 37的找零 是36 或者32 或者27 或者12 的最优解个数+1
var cache = {};
this.makeChange = function(amount) {
var me = this;
if (!amount) {
return [];
}
if (cache[amount]) {
return cache[amount];
}
// min是最优解 newMin是子解 36的子解是(35的最优解 31的最优解 26的最优解 11的最优解)---->类推
var min = [],
newMin, newAmount;
for (var i = 0; i < coins.length; i++) {
var coin = coins[i];
newAmount = amount - coin;
if (newAmount >= 0) {
// 如果刚好找完 newAmount = 0 返回newMin = [];
newMin = me.makeChange(newAmount);
}
if (newAmount >= 0 && (newMin.length < min.length - 1 || !min.length) && (newMin.length || !newAmount)) {
min = [coin].concat(newMin);
}
}
// 每个最优解存储起来
return (cache[amount] = min);
}
this.cache = function() {
console.log(cache);
}
}
var a = new MinCoinChange([1, 5, 10, 25]);
console.log(a.makeChange(36));
js动态规划 找零问题
最新推荐文章于 2024-06-11 10:00:07 发布