給定錢幣的面值 1、5、10、25
需要找給客戶 36
最少找零數為: 1、10、25
// dp[0] = 0 金額為零時不需要硬幣
// dp[n] = min(dp[n],dp[n-coin1] + 1,dp[n-coin2],...) 金額為n時,硬幣數等於(n-coin)+1中所需硬幣最少的組合
function coinChange (coins,amount){
let dp = new Array(amount+1).fill(Infinity);
dp[0] = 0
let path = [];
for(let i = 1; i <= amount; i++){
for(let j = 0; j < coins.length; j++){
let n = i - coins[j];
if(n >= 0){
if(dp[n]+1 < dp[i]){
dp[i] = dp[n]+1;
path[i] = coins[j];
}
}
}
}
let sum = path[amount];
let res = [sum];
amount = amount - sum;
while(amount > 0){
sum = path[amount];
res.push(sum);
amount = amount - sum;
}
console.log(dp,res);
}
coinChange([1,5,10,25],37);
