Skip to content

Commit

Permalink
Create 05. Perfect Squares.py
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed Oct 4, 2022
1 parent 085055b commit 6e607d1
Showing 1 changed file with 39 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# https://leetcode.com/problems/perfect-squares/

'''
# Coin Change
class Solution:
def numSquares(self, n: int) -> int:
row = int(math.sqrt(n)) + 1
dp = [[2**31]*(n+1) for i in range(row)]
for i in range(row):
dp[i][0] = 0
for i in range(1, row):
for j in range(1, n+1):
if i**2 <= j:
dp[i][j] = min(dp[i-1][j], 1 + dp[i][j - i**2])
else:
dp[i][j] = dp[i-1][j]
# print(dp)
return dp[-1][-1]
# Time: O(N * N^1/2)
# Space: O(N * N^1/2)
'''

# 1D DP
# https://youtu.be/HLZLwjzIVGo
class Solution:
def numSquares(self, n: int) -> int:
dp = [n] * (n+1)
dp[0] = 0
for target in range(1, n+1):
for s in range(target):
sq = s * s
if sq > target: break
dp[target] = min(dp[target], 1 + dp[target - sq])

return dp[n]

# Time: O(N * N^1/2)
# Space: O(N)

0 comments on commit 6e607d1

Please sign in to comment.