[LeetCode][Python3] 279. Perfect Squares
2019. 1. 31. 01:05 |
프로그래밍/LeetCode
Problem :
https://leetcode.com/problems/perfect-squares/
My Solution :
class Solution:
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
if n == int(n**0.5)**2:
return 1
squares = []
for a in range(1, int(n**0.5)+1):
squares.append(a**2)
level = 0
queue = {n}
while True:
level += 1
level_queue = set()
for num in queue:
for a in squares:
if a == num:
return level
if a > num:
break
level_queue.add(num - a)
queue = level_queue
Comment :
BFS를 하면서 최초로 square를 만났을 때 level을 리턴하는 전략을 취해보았다.
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 200. Number of Islands (0) | 2019.02.11 |
---|---|
[LeetCode][Python3] 300. Longest Increasing Subsequence (0) | 2019.02.10 |
[LeetCode][Python3] 240. Search a 2D Matrix II (0) | 2019.02.09 |
[LeetCode][Python3] 103. Binary Tree Zigzag Level Order Traversal (0) | 2019.02.07 |
[LeetCode][Python3] 162. Find Peak Element (0) | 2019.01.25 |
[LeetCode][Python3] 328. Odd Even Linked List (0) | 2019.01.25 |
[LeetCode][Python3] 287. Find the Duplicate Number (0) | 2019.01.25 |
[LeetCode][Python3] 75. Sort Colors (0) | 2019.01.24 |
최근에 달린 댓글 최근에 달린 댓글