Files
hello-algo/ja/codes/cpp/chapter_greedy/coin_change_greedy.cpp
T
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

61 lines
2.0 KiB
C++

/**
* File: coin_change_greedy.cpp
* Created Time: 2023-07-20
* Author: krahets ([email protected])
*/
#include "../utils/common.hpp"
/* 硬貨の両替:貪欲法 */
int coinChangeGreedy(vector<int> &coins, int amt) {
// coins リストはソート済みと仮定する
int i = coins.size() - 1;
int count = 0;
// 残額がなくなるまで貪欲な選択を繰り返す
while (amt > 0) {
// 残額より小さく、残額に最も近い硬貨を探す
while (i > 0 && coins[i] > amt) {
i--;
}
// coins[i] を選ぶ
amt -= coins[i];
count++;
}
// 実行可能な方法が見つからなかった場合、-1 を返す
return amt == 0 ? count : -1;
}
/* 実行用コード */
int main() {
// 貪欲法:大域的最適解が得られることを保証できる
vector<int> coins = {1, 5, 10, 20, 50, 100};
int amt = 186;
int res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "目標金額 " << amt << " にするために必要な硬貨の最小枚数は " << res << endl;
// 貪欲法:大域的最適解が得られることを保証できない
coins = {1, 20, 50};
amt = 60;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "目標金額 " << amt << " にするために必要な硬貨の最小枚数は " << res << endl;
cout << "実際に必要な最小枚数は 3 、すなわち 20 + 20 + 20" << endl;
// 貪欲法:大域的最適解が得られることを保証できない
coins = {1, 49, 50};
amt = 98;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "目標金額 " << amt << " にするために必要な硬貨の最小枚数は " << res << endl;
cout << "実際に必要な最小枚数は 2 、すなわち 49 + 49" << endl;
return 0;
}