cpp-algo-cases/chapter_dynamic_programming/coin_change.cpp

71 lines
1.8 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: coin_change.cpp
* Created Time: 2023-07-11
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><>Ǯ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD>̬<EFBFBD>滮 */
int coinChangeDP(vector<int> &coins, int amt) {
int n = coins.size();
int MAX = amt + 1;
// <20><>ʼ<EFBFBD><CABC> dp <20><>
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
// ״̬ת<CCAC>ƣ<EFBFBD><C6A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
for (int a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// ״̬ת<CCAC>ƣ<EFBFBD><C6A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD>к<EFBFBD><D0BA><EFBFBD>
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EEA3AC><EFBFBD><EFBFBD>ѡӲ<D1A1><D3B2> i
dp[i][a] = dp[i - 1][a];
} else {
// <20><>ѡ<EFBFBD><D1A1>ѡӲ<D1A1><D3B2> i <20><><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD>Ľ<EFBFBD>Сֵ
dp[i][a] = min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] != MAX ? dp[n][amt] : -1;
}
/* <20><>Ǯ<EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>滮 */
int coinChangeDPComp(vector<int> &coins, int amt) {
int n = coins.size();
int MAX = amt + 1;
// <20><>ʼ<EFBFBD><CABC> dp <20><>
vector<int> dp(amt + 1, MAX);
dp[0] = 0;
// ״̬ת<CCAC><D7AA>
for (int i = 1; i <= n; i++) {
for (int a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ<EFBFBD><C4BF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EEA3AC><EFBFBD><EFBFBD>ѡӲ<D1A1><D3B2> i
dp[a] = dp[a];
} else {
// <20><>ѡ<EFBFBD><D1A1>ѡӲ<D1A1><D3B2> i <20><><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD><EFBFBD>Ľ<EFBFBD>Сֵ
dp[a] = min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] != MAX ? dp[amt] : -1;
}
/* Driver code */
int main() {
vector<int> coins = {1, 2, 5};
int amt = 4;
// <20><>̬<EFBFBD>
int res = coinChangeDP(coins, amt);
cout << "<EFBFBD>յ<EFBFBD>Ŀ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
// <20>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>
res = coinChangeDPComp(coins, amt);
cout << "<EFBFBD>յ<EFBFBD>Ŀ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
return 0;
}