leetcode 279. Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

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
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
if n < 2:return n
lst = []
for i in range(1,n):
if i*i <= n:
lst.append(i*i)
else:break
cnt = 0
nums = {n}
while nums:
temp =set()
cnt += 1
for x in nums:
for y in lst:
if x == y :
return cnt
elif x < y:break
temp.add(x-y)
nums = temp
return cnt