Skip to content

Commit 3193d16

Browse files
committed
添加0279.完全平方数 Python版本
1 parent 7f8b0a1 commit 3193d16

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

problems/0279.完全平方数.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,27 @@ class Solution:
271271
# 返回结果
272272
return dp[n]
273273

274+
```
275+
```python
276+
class Solution(object):
277+
def numSquares(self, n):
278+
# 先把可以选的数准备好,更好理解
279+
nums, num = [], 1
280+
while num ** 2 <= n:
281+
nums.append(num ** 2)
282+
num += 1
283+
# dp数组初始化
284+
dp = [float('inf')] * (n + 1)
285+
dp[0] = 0
274286

287+
# 遍历准备好的完全平方数
288+
for i in range(len(nums)):
289+
# 遍历背包容量
290+
for j in range(nums[i], n+1):
291+
dp[j] = min(dp[j], dp[j-nums[i]]+1)
292+
# 返回结果
293+
return dp[-1]
294+
275295

276296
```
277297
### Go:

0 commit comments

Comments
 (0)