mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-02 11:15:19 +08:00
* 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
69 lines
2.0 KiB
C++
69 lines
2.0 KiB
C++
/**
|
|
* File: coin_change_ii.cpp
|
|
* Created Time: 2023-07-11
|
|
* Author: krahets ([email protected])
|
|
*/
|
|
|
|
#include "../utils/common.hpp"
|
|
|
|
/* 硬貨の両替 II:動的計画法 */
|
|
int coinChangeIIDP(vector<int> &coins, int amt) {
|
|
int n = coins.size();
|
|
// dp テーブルを初期化する
|
|
vector<vector<int>> dp(n + 1, vector<int>(amt + 1, 0));
|
|
// 先頭列を初期化する
|
|
for (int i = 0; i <= n; i++) {
|
|
dp[i][0] = 1;
|
|
}
|
|
// 状態遷移
|
|
for (int i = 1; i <= n; i++) {
|
|
for (int a = 1; a <= amt; a++) {
|
|
if (coins[i - 1] > a) {
|
|
// 目標金額を超える場合、硬貨 i を選ばない
|
|
dp[i][a] = dp[i - 1][a];
|
|
} else {
|
|
// 硬貨 i を選ばない場合と選ぶ場合の方法の数の和
|
|
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
|
}
|
|
}
|
|
}
|
|
return dp[n][amt];
|
|
}
|
|
|
|
/* 硬貨の両替 II:空間を最適化した動的計画法 */
|
|
int coinChangeIIDPComp(vector<int> &coins, int amt) {
|
|
int n = coins.size();
|
|
// dp テーブルを初期化する
|
|
vector<int> dp(amt + 1, 0);
|
|
dp[0] = 1;
|
|
// 状態遷移
|
|
for (int i = 1; i <= n; i++) {
|
|
for (int a = 1; a <= amt; a++) {
|
|
if (coins[i - 1] > a) {
|
|
// 目標金額を超える場合、硬貨 i を選ばない
|
|
dp[a] = dp[a];
|
|
} else {
|
|
// 硬貨 i を選ばない場合と選ぶ場合の方法の数の和
|
|
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
|
}
|
|
}
|
|
}
|
|
return dp[amt];
|
|
}
|
|
|
|
/* 実行用コード */
|
|
int main() {
|
|
vector<int> coins = {1, 2, 5};
|
|
int amt = 5;
|
|
|
|
// 動的計画法
|
|
int res = coinChangeIIDP(coins, amt);
|
|
cout << "目標金額になる硬貨の組み合わせの数は " << res << endl;
|
|
|
|
// 空間を最適化した動的計画法
|
|
res = coinChangeIIDPComp(coins, amt);
|
|
cout << "目標金額になる硬貨の組み合わせの数は " << res << endl;
|
|
|
|
return 0;
|
|
}
|