일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- Convert Sorted List to Binary Search Tree
- Class
- iterator
- Protocol
- Regular Expression
- 30. Substring with Concatenation of All Words
- data science
- 파이썬
- attribute
- kaggle
- Python Implementation
- Generator
- concurrency
- Python
- 315. Count of Smaller Numbers After Self
- Decorator
- 시바견
- 컴퓨터의 구조
- shiba
- t1
- 밴픽
- 109. Convert Sorted List to Binary Search Tree
- 운영체제
- 43. Multiply Strings
- 715. Range Module
- 프로그래머스
- Python Code
- Substring with Concatenation of All Words
- LeetCode
- DWG
Archives
- Today
- Total
Scribbling
LeetCode: 279. Perfect Squares 본문
O(N**2) Time Complexity, O(N) Memory
Not an effective solution at all especially in terms of time complexity.
class Solution:
def numSquares(self, n: int) -> int:
INT_MAX = int(1e5)
dp = [INT_MAX] * (n+1)
x = 1
while x * x <= n:
dp[x*x] = 1
x += 1
for i in range(1, n+1):
if dp[i] != INT_MAX:
continue
for j in range(i//2, i):
dp[i] = min(dp[i], dp[j]+dp[i-j])
return dp[n]
A nice approach would be BFS.
Time Complexity is O(N) as the worst scenario here is adding up 1s. (Deepest route is 1+1+1+...+1)
Memory Complexity is O(N*sqrt(N)) as we have sqrt(N) perfect square numbers and the height of the tree will be N at worst.
class Solution:
def numSquares(self, n: int) -> int:
psns = []
x = 1
while x * x <= n:
psns.append(x*x)
x += 1
nums, cnt = {n}, 0
while nums:
next_nums = set()
cnt += 1
for num in nums:
for psn in psns:
if psn == num:
return cnt
if num < psn:
break
next_nums.add(num-psn)
nums = next_nums
DP Solution
Time Complexity is O(N*sqrt(N))
Memory Complexity is O(N)
class Solution:
def numSquares(self, n: int) -> int:
INT_MAX = int(1e5)
dp = [INT_MAX] * (n+1)
dp[0] = 0
for i in range(1, n+1):
for j in range(1, int(i**0.5)+1):
dp[i] = min(dp[i], dp[i-j*j]+1)
return dp[n]
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 289. Game of Life (0) | 2021.12.29 |
---|---|
LeetCode: 287. Find the Duplicate Number (0) | 2021.12.28 |
LeetCode: 240. Search a 2D Matrix II (0) | 2021.12.27 |
LeetCode: 283. Move Zeroes (0) | 2021.12.25 |
LeetCode: 234. Palindrome Linked List (0) | 2021.12.24 |