From f45d4718c39c6d932ef32ff190c01be839a7d18d Mon Sep 17 00:00:00 2001 From: fwqaaq Date: Mon, 29 May 2023 19:10:46 +0800 Subject: [PATCH] =?UTF-8?q?Update=200322.=E9=9B=B6=E9=92=B1=E5=85=91?= =?UTF-8?q?=E6=8D=A2.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0322.零钱兑换.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0322.零钱兑换.md b/problems/0322.零钱兑换.md index 28188349..0f910451 100644 --- a/problems/0322.零钱兑换.md +++ b/problems/0322.零钱兑换.md @@ -336,6 +336,28 @@ impl Solution { } ``` +```rust +// 遍历背包 +impl Solution { + pub fn coin_change(coins: Vec, amount: i32) -> i32 { + let amount = amount as usize; + let mut dp = vec![i32::MAX; amount + 1]; + dp[0] = 0; + for i in 0..=amount { + for &coin in &coins { + if i >= coin as usize && dp[i - coin as usize] != i32::MAX { + dp[i] = dp[i].min(dp[i - coin as usize] + 1) + } + } + } + if dp[amount] == i32::MAX { + return -1; + } + dp[amount] + } +} +``` + Javascript: ```javascript const coinChange = (coins, amount) => {