forked from SamirPaulb/DSAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
085055b
commit 6e607d1
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
02_Dynamic-Programming/02. Unobunded Knapsack/05. Perfect Squares.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |