From aa0bf782221988b204b764767ae50571d63ab145 Mon Sep 17 00:00:00 2001 From: Wen <409053122@qq.com> Date: Fri, 20 Jun 2025 23:10:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=9B=B6=E9=92=B1=E5=85=91=E6=8D=A2(?= =?UTF-8?q?=E8=83=8C=E5=8C=85dp)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leecode/dp/No322.java | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/leecode/dp/No322.java diff --git a/src/leecode/dp/No322.java b/src/leecode/dp/No322.java new file mode 100644 index 0000000..d43a333 --- /dev/null +++ b/src/leecode/dp/No322.java @@ -0,0 +1,30 @@ +package leecode.dp; + +import java.util.Arrays; + +/** + * 322. 零钱兑换 + * @author Wen + * @date 2025/6/20 23:09 + */ +public class No322 { + public int coinChange(int[] coins, int amount) { + if (amount == 0) { + return 0; + } + int[] dp = new int[amount + 1]; + // 如果能匹配到对应的硬币组合,硬币数一定小于amount+1个 + Arrays.fill(dp, amount + 1); + dp[0] = 0; + for (int i = 1; i <= amount; i ++) { + for (int j = 0; j < coins.length; j ++) { + // 遍历当前每个硬币值,认为当前取该枚硬币,然后找(i-当前硬币值)后的子解最小值 + if (i >= coins[j]) { + dp[i] = Math.min(dp[i - coins[j]] + 1, dp[i]); + } + } + } + // 如果dp[amount]为初始值,说明子问题中没有找到解 + return dp[amount] == amount + 1 ? -1 : dp[amount]; + } +}