cpp-algo-cases/chapter_greedy/coin_change_greedy.cpp

61 lines
1.6 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: coin_change_greedy.cpp
* Created Time: 2023-07-20
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>Ǯ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD>̰<EFBFBD><CCB0> */
int coinChangeGreedy(vector<int> &coins, int amt) {
// <20><><EFBFBD><EFBFBD> coins <20>б<EFBFBD><D0B1><EFBFBD><EFBFBD><EFBFBD>
int i = coins.size() - 1;
int count = 0;
// ѭ<><D1AD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>̰<EFBFBD><CCB0>ѡ<EFBFBD><D1A1><EFBFBD><EFBFBD>ֱ<EFBFBD><D6B1><EFBFBD><EFBFBD>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
while (amt > 0) {
// <20>ҵ<EFBFBD>С<EFBFBD><D0A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ӽ<EFBFBD>ʣ<EFBFBD><CAA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><D3B2>
while (i > 0 && coins[i] > amt) {
i--;
}
// ѡ<><D1A1> coins[i]
amt -= coins[i];
count++;
}
// <20><>δ<EFBFBD>ҵ<EFBFBD><D2B5><EFBFBD><EFBFBD>з<EFBFBD><D0B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD>򷵻<EFBFBD> -1
return amt == 0 ? count : -1;
}
/* Driver Code */
int main() {
// ̰<>ģ<EFBFBD><C4A3>ܹ<EFBFBD><DCB9><EFBFBD>֤<EFBFBD>ҵ<EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD>Ž<EFBFBD>
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 << "<EFBFBD>յ<EFBFBD> " << amt << " <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><D3B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
// ̰<>ģ<EFBFBD><C4A3>޷<EFBFBD><DEB7><EFBFBD>֤<EFBFBD>ҵ<EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD>Ž<EFBFBD>
coins = {1, 20, 50};
amt = 60;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "<EFBFBD>յ<EFBFBD> " << amt << " <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><D3B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
cout << "ʵ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ 3 <20><><EFBFBD><EFBFBD> 20 + 20 + 20" << endl;
// ̰<>ģ<EFBFBD><C4A3>޷<EFBFBD><DEB7><EFBFBD>֤<EFBFBD>ҵ<EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD><EFBFBD>Ž<EFBFBD>
coins = {1, 49, 50};
amt = 98;
res = coinChangeGreedy(coins, amt);
cout << "\ncoins = ";
printVector(coins);
cout << "amt = " << amt << endl;
cout << "<EFBFBD>յ<EFBFBD> " << amt << " <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><D3B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
cout << "ʵ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ 2 <20><><EFBFBD><EFBFBD> 49 + 49" << endl;
return 0;
}