69 lines
1.7 KiB
C++
69 lines
1.7 KiB
C++
|
/**
|
|||
|
* File: coin_change_ii.cpp
|
|||
|
* Created Time: 2023-07-11
|
|||
|
* Author: krahets (krahets@163.com)
|
|||
|
*/
|
|||
|
|
|||
|
#include "../utils/common.hpp"
|
|||
|
|
|||
|
/* <20><>Ǯ<EFBFBD>һ<EFBFBD> II<49><49><EFBFBD><EFBFBD>̬<EFBFBD>滮 */
|
|||
|
int coinChangeIIDP(vector<int> &coins, int amt) {
|
|||
|
int n = coins.size();
|
|||
|
// <20><>ʼ<EFBFBD><CABC> dp <20><>
|
|||
|
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
|||
|
// <20><>ʼ<EFBFBD><CABC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
|
|||
|
for (int i = 0; i <= n; i++) {
|
|||
|
dp[i][0] = 1;
|
|||
|
}
|
|||
|
// ״̬ת<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[i][a] = dp[i - 1][a];
|
|||
|
} else {
|
|||
|
// <20><>ѡ<EFBFBD><D1A1>ѡӲ<D1A1><D3B2> i <20><><EFBFBD><EFBFBD><EFBFBD>ַ<EFBFBD><D6B7><EFBFBD>֮<EFBFBD><D6AE>
|
|||
|
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
return dp[n][amt];
|
|||
|
}
|
|||
|
|
|||
|
/* <20><>Ǯ<EFBFBD>һ<EFBFBD> II<49><49><EFBFBD>ռ<EFBFBD><D5BC>Ż<EFBFBD><C5BB><EFBFBD><EFBFBD>Ķ<EFBFBD>̬<EFBFBD>滮 */
|
|||
|
int coinChangeIIDPComp(vector<int> &coins, int amt) {
|
|||
|
int n = coins.size();
|
|||
|
// <20><>ʼ<EFBFBD><CABC> dp <20><>
|
|||
|
vector<int> dp(amt + 1, 0);
|
|||
|
dp[0] = 1;
|
|||
|
// ״̬ת<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><D6AE>
|
|||
|
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
return dp[amt];
|
|||
|
}
|
|||
|
|
|||
|
/* Driver code */
|
|||
|
int main() {
|
|||
|
vector<int> coins = {1, 2, 5};
|
|||
|
int amt = 5;
|
|||
|
|
|||
|
// <20><>̬<EFBFBD>滮
|
|||
|
int res = coinChangeIIDP(coins, amt);
|
|||
|
cout << "<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 = coinChangeIIDPComp(coins, amt);
|
|||
|
cout << "<EFBFBD>ճ<EFBFBD>Ŀ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ӳ<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ " << res << endl;
|
|||
|
|
|||
|
return 0;
|
|||
|
}
|