function minCoinChange(coins, amount) {
const cache = {}
const makeChange = (value) => {
//若amount <= 0 返回空数组
if (!value) {
return []
}
//缓存中存在直接返回
if (cache[value]) {
return cache[value]
}
let min = []
let newMin
let newAmount
for (let i = 0; i < coins.length; i++) {
const coin = coins[i]
newAmount = value - coin
//传入0会返回空数组 所以这里>=0
if (newAmount >= 0) {
newMin = makeChange(newAmount)
}
if (newAmount >= 0 &&
//因为newMin需要加上coin然后小于min
//newMIn + 1 < min
//newMin < min - 1
(newMin.length < min.length - 1 || !min.length)
&& (newMin.length || newAmount)) {
min = [coin].concat(newMin)
}
}
return (cache[value] = min)
}
return makeChange(amount)
}
console.log(minCoinChange([1, 5, 10, 25], 1));
// 1 []