mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加0279.完全平方数 Python版本
This commit is contained in:
@ -271,6 +271,26 @@ class Solution:
|
|||||||
# 返回结果
|
# 返回结果
|
||||||
return dp[n]
|
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]
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user