代码改变世界

js贪心算法---钱币找零问题

2018-07-17 14:53  muamaker  阅读(944)  评论(0编辑  收藏  举报
		function MinCoinChange(coins){
			var coins = coins.sort(function(a,b){
				return b - a;
			});
		
			this.makeChange = function(amount){
				var change = [],
				total = 0;
				for (var i = 0; i < coins.length; i++){ 
					var coin = coins[i];
					while (total + coin <= amount) {
					change.push(coin); 
					total += coin; 
					}
					}
				return change;
			}
		}
		var coin =  new MinCoinChange([1,2,5,10]);
		console.log(coin.makeChange(36));