兩大關鍵性質:
硬幣面值:25分、10分、5分、1分。目標:用最少硬幣數找零 n 分。
貪婪策略:優先使用最大面值硬幣。
// 找零算法
public static int[] changeCoins(int[] coins, int amount) {
int[] count = new int[coins.length];
for (int i = 0; i < coins.length; i++) {
count[i] = amount / coins[i];
amount %= coins[i];
}
return count;
}
// 測試
public static void main(String[] args) {
int[] coins = {25, 10, 5, 1};
int amount = 99;
int[] result = changeCoins(coins, amount);
for (int i = 0; i < coins.length; i++) {
System.out.println(result[i] + " 枚 " + coins[i] + " 分");
}
}
// 輸出:
// 3 枚 25 分
// 2 枚 10 分
// 0 枚 5 分
// 4 枚 1 分
並非所有面值組合都適用貪婪策略(如面值 25, 20, 1 找 40 分,貪婪得 25+1×15=16 枚,最優為 20×2=2 枚)。實際應用前需證明貪婪選擇性質成立。
Greedy(C) // C 為候選集合
S = {} // 解集合
while not solution(S):
x = select(C) // 貪婪選擇
if feasible(S, x):
S = S ∪ {x}
C = C \ {x}
return S