一、Greedy Algorithm
1.1 基本觀念介紹
Greedy Algorithm (貪婪演算法) 是指在對問題求解時,總是做出在當前看起來最好的選擇,所以此種演算法在解問題時,不是所有題型都能得到 global optimization (全域最佳解),但對於相當多問題能產生整體最佳解或者是近似整體最佳解。
總之貪婪演算法的精神就是 : 短視近利、今朝有酒今朝醉,每一步面臨選擇時,都做眼前最有利的選擇,不考慮對將來是否有不良的影響,與 dynamic programming 不同,不會保留計算結果。
假設現在有個金額 M,有 1、5、10、20、50 元這些幣值種類,要盡可能用最少的錢幣湊到金額 M。根據貪婪演算法,能用 50 的就盡量用 50 的,否則盡量用 20 的...以此類推;在這種策略下,M 若是 15 則等於 10 * 1 + 5 * 1,共使用了 2 種錢幣。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let normalCoins = [1, 5, 10, 20, 50]; | |
let moneyForGreedy = function (coins, amount) { | |
let coinsLeng = coins.length; | |
let number = []; | |
for (let i = coinsLeng - 1; i >= 0; i--) { | |
number[i] = Math.floor(amount / coins[i]); | |
amount = amount - number[i] * coins[i]; | |
} | |
return number.reduce((a, b) => a + b); | |
}; | |
console.log(moneyForGreedy(normalCoins, 15)); // 2 |
但是如果我們換一組錢幣的種類如 1、5、11,貪婪演算法可能就不是最佳解。
或是我們有一個最多能背重量為 W 的背包,現在有 N 件物品,每件物品只能用一次且價值不相等,求解將哪些物品裝入背包裡物品價值總和最大,這時候因為要同時考慮重量和價值,也沒辦法用貪婪就取得最佳解。
這在下一篇 Dynamic Programming (動態規劃) 會講解到。