Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.
Example 1:
Input: n =12
Output: 3 Explanation:12 = 4 + 4 + 4.
Example 2:
Input: n =13
Output: 2 Explanation:13 = 4 + 9.
-------------------------------------------------------------
BFS code is straightfoward...
朗格朗日四平方定理:
每个正整数均可表示成不超过四个整数的平方之和
重要的推论:
1. 数 n 如果只能表示成四个非零整数的平方和的充要条件是 4^a(8b+7),其中a>=0, b>=0
2. 如果 n%4==0,k=n/4,n 和 k 可由相同个数的整数表示
那么代码是:
class Solution:
def is_square(self, n):
num = math.floor(math.sqrt(n))
return num*num == n
def is_2_square(self, n):
num = math.floor(math.sqrt(n//2))
for i in range(1,num+1):
if (self.is_square(n-i*i)):
return True
return False
def numSquares(self, n):
if (self.is_square(n)):
return 1
elif (self.is_2_square(n)):
return 2
while (n % 4 == 0):
n = n//4
if (n >= 7 and (n-7) % 8 == 0):
return 4
return 3