-
Notifications
You must be signed in to change notification settings - Fork 44
/
perfect-squares.py
104 lines (99 loc) · 2.61 KB
/
perfect-squares.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# V0
# IDEA : BFS
class Solution(object):
def numSquares(self, n):
if n < 2:
return n
lst = []
i = 1
while i * i <= n:
lst.append( i * i )
i += 1
cnt = 0
toCheck = {n}
while toCheck:
cnt += 1
temp = set()
for x in toCheck:
for y in lst:
if x == y:
return cnt
if x < y:
break
temp.add(x-y)
toCheck = temp
return cnt
# V1
# http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/
# time out error
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
dp = collections.defaultdict(int)
y = 1
while y * y <= n:
dp[y * y] = 1
y += 1
for x in range(1, n + 1):
y = 1
while x + y * y <= n:
if x + y * y not in dp or dp[x] + 1 < dp[x + y * y]:
dp[x + y * y] = dp[x] + 1
y += 1
return dp[n]
### Test case : dev
# V1'
# IDEA : DP
# http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/
# https://leetcode.com/problems/perfect-squares/discuss/71512/Static-DP-C%2B%2B-12-ms-Python-172-ms-Ruby-384-ms
class Solution(object):
_dp = [0]
def numSquares(self, n):
dp = self._dp
while len(dp) <= n:
dp += min(dp[-i*i] for i in range(1, int(len(dp)**0.5+1))) + 1
return dp[n]
# V1''
# IDEA : BFS
# https://leetcode.com/problems/perfect-squares/discuss/71475/Short-Python-solution-using-BFS
# IDEA : -> CHECK the LC discussion pic (BFS)
class Solution(object):
def numSquares(self, n):
if n < 2:
return n
lst = []
i = 1
while i * i <= n:
lst.append( i * i )
i += 1
cnt = 0
toCheck = {n}
while toCheck:
cnt += 1
temp = set()
for x in toCheck:
for y in lst:
if x == y:
return cnt
if x < y:
break
temp.add(x-y)
toCheck = temp
return cnt
# V2
# Time: O(n * sqrt(n))
# Space: O(n)
class Solution(object):
_num = [0]
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
num = self._num
while len(num) <= n:
num += min(num[-i*i] for i in range(1, int(len(num)**0.5+1))) + 1
return num[n]