-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path279.py
38 lines (37 loc) · 1001 Bytes
/
279.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
# https://leetcode.com/problems/perfect-squares/description/
# bottom up 1-D DP
# Time: O(N^2)
# Space: O(N)
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
for j in range(1, i + 1):
sq = j ** 2
if sq > i:
break
dp[i] = min(dp[i], dp[i - sq] + 1)
return dp[n]
# top down 1-D DP
# Time: O(N^2)
# Space: O(N)
class Solution:
def numSquares(self, n: int) -> int:
dp = {}
def dfs(k):
if k == 0:
return 0
if k == 1:
return 1
if k in dp:
return dp[k]
res = float('inf')
for i in range(1, k):
if i ** 2 > k:
break
res = min(res, dfs(k - i ** 2) + 1)
dp[k] = res
return res
res = dfs(n)
return res