mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 20:40:39 +08:00
Update 0279.完全平方数.md
This commit is contained in:
@ -231,6 +231,22 @@ class Solution:
|
|||||||
|
|
||||||
return dp[n]
|
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
|
```python
|
||||||
|
Reference in New Issue
Block a user