Skip to content

Commit 298b205

Browse files
authored
Create perfectSquares.py
1 parent 35a75a4 commit 298b205

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Kangli/DP/perfectSquares.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
sample 3626 ms submission
2+
class Solution(object):
3+
def numSquares(self, n)
4+
#這題用dp來做 dp[i]儲存數字i由幾個square number組成 dp[i]=min(dp[i-1*1],dp[i-2*2],...)+1
5+
dp=[0 for i in range(n+1)]
6+
for i in range(1,n+1):
7+
j=1
8+
minv=2147483647
9+
if math.sqrt(i)-int(math.sqrt(i))==0:
10+
dp[i]=1
11+
continue
12+
while i-j*j>=0:
13+
if minv>dp[i-j*j]:
14+
minv=dp[i-j*j]
15+
j+=1
16+
dp[i]=minv+1
17+
return dp[n]

0 commit comments

Comments
 (0)