Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 56045e0

Browse files
Merge pull request #448 from EnzoSeason/leetcode-279
update 279.完全平方数: 提供新的初始化方法
2 parents 328ffcc + 5e68f30 commit 56045e0

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

‎problems/0279.完全平方数.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,26 @@ class Solution:
214214
return dp[n]
215215
```
216216

217+
Python3:
218+
```python
219+
class Solution:
220+
def numSquares(self, n: int) -> int:
221+
# 初始化
222+
# 组成和的完全平方数的最多个数,就是只用1构成
223+
# 因此,dp[i] = i
224+
dp = [i for i in range(n + 1)]
225+
# dp[0] = 0 无意义,只是为了方便记录特殊情况:
226+
# n本身就是完全平方数,dp[n] = min(dp[n], dp[n - n] + 1) = 1
227+
228+
for i in range(1, n): # 遍历物品
229+
if i * i > n:
230+
break
231+
num = i * i
232+
for j in range(num, n + 1): # 遍历背包
233+
dp[j] = min(dp[j], dp[j - num] + 1)
217234

218-
235+
return dp[n]
236+
```
219237

220238
Go:
221239
```go

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /