js动态规划---最少硬币找零问题
2018-07-09 16:17 muamaker 阅读(2793) 评论(0) 编辑 收藏 举报给定钱币的面值 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);