diff --git a/problems/0279.完全平方数.md b/problems/0279.完全平方数.md index f7c06dbd..1b29626f 100644 --- a/problems/0279.完全平方数.md +++ b/problems/0279.完全平方数.md @@ -271,7 +271,27 @@ class Solution: # 返回结果 return dp[n] +``` +```python +class Solution(object): + def numSquares(self, n): + # 先把可以选的数准备好,更好理解 + nums, num = [], 1 + while num ** 2 <= n: + nums.append(num ** 2) + num += 1 + # dp数组初始化 + dp = [float('inf')] * (n + 1) + dp[0] = 0 + # 遍历准备好的完全平方数 + for i in range(len(nums)): + # 遍历背包容量 + for j in range(nums[i], n+1): + dp[j] = min(dp[j], dp[j-nums[i]]+1) + # 返回结果 + return dp[-1] + ``` ### Go: