貪心算法可以說是對算法本身非常完美的解釋了。即將問題分拆為若干子問題媳维,再各自求出子問題的最優(yōu)解底扳,而后將最優(yōu)解組合铸抑。相對來說格局不如【動態(tài)規(guī)劃】格局大,個人目前感覺比較偏向單線程衷模。
'use strict';
// coins 表示擁有的硬幣種類
// 局部最優(yōu)之和
// 缺點: 6得到是[4,1,1] 而不是[3,3]
class minChangeQues {
constructor (coins) {
this.coins = coins;
}
changeCoins(amount) {
let change = []
let total = 0
for (let i = this.coins.length - 1; i >= 0; i --) {
let coin = this.coins[i]
while (coin + total <= amount) {
change.push(coin)
total += coin
}
}
return change
}
}
let temp = new minChangeQues([1,5,10,25])
console.log(temp.changeCoins(50));
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者