js動態規划---最少硬幣找零問題


給定錢幣的面值 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);

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM