279 Perfect Squares
class Node:
def __init__(self, num, remainder, count):
self.num = num
self.remainder = remainder
self.count = count
class Solution(object):
def __gatherPerfectSquares(self, n):
"""
:param n: up to <= n
:return: List[int] of perfect squares
"""
return [i*i for i in range(1,n+1) if i*i <= n]
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
squares = self.__gatherPerfectSquares(n)
top = Node(n, n, 0)
stack = [top]
the_min = 9999
while len(stack) > 0:
top = stack.pop()
# Lagrange's four-square theorem
if top.count >= 4:
continue
options = [num for num in squares if num <= top.remainder]
for opt in options:
remainder = top.remainder - opt
if remainder == 0:
the_min = min(the_min, top.count + 1)
stack.append(Node(opt, remainder, top.count + 1))
return the_minLast updated