File tree Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change 26
26
输入:n = 13
27
27
输出:2
28
28
解释:13 = 4 + 9
29
-
29
+
30
30
提示:
31
31
* 1 <= n <= 10^4
32
32
@@ -184,6 +184,38 @@ class Solution {
184
184
185
185
Python:
186
186
187
+ ``` python3
188
+ class Solution :
189
+ def numSquares (self , n : int ) -> int :
190
+ ''' 版本一'''
191
+ # 初始化
192
+ nums = [i** 2 for i in range (1 , n + 1 ) if i** 2 <= n]
193
+ dp = [10 ** 4 ]* (n + 1 )
194
+ dp[0 ] = 0
195
+ # 遍历背包
196
+ for j in range (1 , n + 1 ):
197
+ # 遍历物品
198
+ for num in nums:
199
+ if j >= num:
200
+ dp[j] = min (dp[j], dp[j - num] + 1 )
201
+ return dp[n]
202
+
203
+ def numSquares1 (self , n : int ) -> int :
204
+ ''' 版本二'''
205
+ # 初始化
206
+ nums = [i** 2 for i in range (1 , n + 1 ) if i** 2 <= n]
207
+ dp = [10 ** 4 ]* (n + 1 )
208
+ dp[0 ] = 0
209
+ # 遍历物品
210
+ for num in nums:
211
+ # 遍历背包
212
+ for j in range (num, n + 1 )
213
+ dp[j] = min (dp[j], dp[j - num] + 1 )
214
+ return dp[n]
215
+ ```
216
+
217
+
218
+
187
219
188
220
Go:
189
221
``` go
You can’t perform that action at this time.
0 commit comments