From 89c197b9eb38bde9c91390ed85299af3b9384962 Mon Sep 17 00:00:00 2001 From: linlihong <747682928@qq.com> Date: Wed, 25 Sep 2024 15:30:50 +0800 Subject: [PATCH] =?UTF-8?q?2024/9/25=20Hot100=20dp=20=E6=98=A8=E6=97=A5?= =?UTF-8?q?=E6=9C=AA=E5=AE=8C=E6=88=90=E7=9A=84dp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/cool/hot100/dp/Num279.java | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/main/java/com/cool/hot100/dp/Num279.java b/src/main/java/com/cool/hot100/dp/Num279.java index b069583..474db00 100644 --- a/src/main/java/com/cool/hot100/dp/Num279.java +++ b/src/main/java/com/cool/hot100/dp/Num279.java @@ -2,7 +2,9 @@ package com.cool.hot100.dp; import org.junit.Test; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; /** * Created with IntelliJ IDEA. @@ -63,4 +65,24 @@ public class Num279 { return memory[i][j] = Math.min(dfs(i - 1, j), dfs(i, j - i * i) + 1); } + /** + * + * 可以类比成为完全背包的零钱问题,把n之前的平方数当作一个个硬币,n是当前有的零钱,则可套用一样的逻辑 + * @param n + * @return + */ + public int numSquares2(int n) { + int[] dp = new int[n + 1]; + // 初始化 dp 数组 + Arrays.fill(dp, Integer.MAX_VALUE); + dp[0] = 0; + for (int i = 1; i * i <= n; i++) { + for (int j = i * i; j <= n; j++) { + dp[j] = Math.min(dp[j], dp[j - i * i] + 1); + } + } + return dp[n]; + } + + }