From 45037cec331a3c924a54a24a279e5d0b6d342361 Mon Sep 17 00:00:00 2001 From: jianghongcheng <35664721+jianghongcheng@users.noreply.github.com> Date: Mon, 5 Jun 2023 00:05:11 -0500 Subject: [PATCH] =?UTF-8?q?Update=200279.=E5=AE=8C=E5=85=A8=E5=B9=B3?= =?UTF-8?q?=E6=96=B9=E6=95=B0.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0279.完全平方数.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index b26f981c..80b69f0c 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -231,6 +231,22 @@ class Solution: return dp[n] +``` +先遍历背包, 再遍历物品 +```python +class Solution: + def numSquares(self, n: int) -> int: + dp = [float('inf')] * (n + 1) + dp[0] = 0 + + for i in range(1, int(n ** 0.5) + 1): # 遍历物品 + for j in range(i * i, n + 1): # 遍历背包 + # 更新凑成数字 j 所需的最少完全平方数数量 + dp[j] = min(dp[j - i * i] + 1, dp[j]) + + return dp[n] + + ``` 其他版本 ```python