-
Medium
-
Given an integer
n
, return the least number of perfect square numbers that sum ton
.A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example,
1
,4
,9
, and16
are perfect squares while3
and11
are not.
A BFS would give the solution to this problem. In searching, we want to see if a level of the tree can satisfy the result, if not, we move on to the next level with one more number to add. The tree would look like the following:
class Solution:
def numSquares(self, n):
if n < 2:
return n
lst = []
i = 1
while i * i <= n:
lst.append( i * i )
i += 1
cnt = 0
toCheck = {n}
while toCheck:
cnt += 1
temp = set()
for x in toCheck:
for y in lst:
if x == y:
return cnt
if x < y:
break
temp.add(x-y)
toCheck = temp
return cnt