2023-07-15 23:16:02 +08:00
|
|
|
|
/*
|
|
|
|
|
* File: coin_change_ii.rs
|
|
|
|
|
* Created Time: 2023-07-09
|
2024-01-02 01:25:37 +08:00
|
|
|
|
* Author: codingonion (coderonion@gmail.com)
|
2023-07-15 23:16:02 +08:00
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
/* 零钱兑换 II:动态规划 */
|
|
|
|
|
fn coin_change_ii_dp(coins: &[i32], amt: usize) -> i32 {
|
|
|
|
|
let n = coins.len();
|
|
|
|
|
// 初始化 dp 表
|
|
|
|
|
let mut dp = vec![vec![0; amt + 1]; n + 1];
|
|
|
|
|
// 初始化首列
|
2024-03-16 02:13:41 +08:00
|
|
|
|
for i in 0..=n {
|
2023-07-15 23:16:02 +08:00
|
|
|
|
dp[i][0] = 1;
|
|
|
|
|
}
|
|
|
|
|
// 状态转移
|
|
|
|
|
for i in 1..=n {
|
|
|
|
|
for a in 1..=amt {
|
|
|
|
|
if coins[i - 1] > a as i32 {
|
2023-11-03 22:48:43 +08:00
|
|
|
|
// 若超过目标金额,则不选硬币 i
|
2023-07-15 23:16:02 +08:00
|
|
|
|
dp[i][a] = dp[i - 1][a];
|
|
|
|
|
} else {
|
2024-01-06 14:47:32 +08:00
|
|
|
|
// 不选和选硬币 i 这两种方案之和
|
2023-07-15 23:16:02 +08:00
|
|
|
|
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1] as usize];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
dp[n][amt]
|
|
|
|
|
}
|
|
|
|
|
|
2023-08-27 00:50:18 +08:00
|
|
|
|
/* 零钱兑换 II:空间优化后的动态规划 */
|
2023-07-26 11:00:53 +08:00
|
|
|
|
fn coin_change_ii_dp_comp(coins: &[i32], amt: usize) -> i32 {
|
2023-07-15 23:16:02 +08:00
|
|
|
|
let n = coins.len();
|
|
|
|
|
// 初始化 dp 表
|
|
|
|
|
let mut dp = vec![0; amt + 1];
|
|
|
|
|
dp[0] = 1;
|
|
|
|
|
// 状态转移
|
|
|
|
|
for i in 1..=n {
|
|
|
|
|
for a in 1..=amt {
|
|
|
|
|
if coins[i - 1] > a as i32 {
|
2023-11-03 22:48:43 +08:00
|
|
|
|
// 若超过目标金额,则不选硬币 i
|
2023-07-15 23:16:02 +08:00
|
|
|
|
dp[a] = dp[a];
|
|
|
|
|
} else {
|
2024-01-06 14:47:32 +08:00
|
|
|
|
// 不选和选硬币 i 这两种方案之和
|
2023-07-15 23:16:02 +08:00
|
|
|
|
dp[a] = dp[a] + dp[a - coins[i - 1] as usize];
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
dp[amt]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/* Driver Code */
|
|
|
|
|
pub fn main() {
|
2024-03-16 02:13:41 +08:00
|
|
|
|
let coins = [1, 2, 5];
|
2023-07-15 23:16:02 +08:00
|
|
|
|
let amt: usize = 5;
|
|
|
|
|
|
|
|
|
|
// 动态规划
|
|
|
|
|
let res = coin_change_ii_dp(&coins, amt);
|
|
|
|
|
println!("凑出目标金额的硬币组合数量为 {res}");
|
|
|
|
|
|
2023-08-27 00:50:18 +08:00
|
|
|
|
// 空间优化后的动态规划
|
2023-08-31 02:33:13 +08:00
|
|
|
|
let res = coin_change_ii_dp_comp(&coins, amt);
|
2023-07-15 23:16:02 +08:00
|
|
|
|
println!("凑出目标金额的硬币组合数量为 {res}");
|
|
|
|
|
}
|