先算小于N的完全平方数,再用这些数做广度优先:
class Solution:
def numSquares(self, n: int) -> int:
if n == 0:
return 0
tempNum = []
x = 1
i = 1
#计算小于n的完全平方数
while x <= n:
tempNum.append(x)
i += 1
x = pow(i, 2)
from collections import deque
stack = deque([[n, 0]])
while stack: #使用广度优先算法遍历每层
num, level = stack.popleft()
for i in tempNum:
temp = num - i
if temp > 0:
stack.append([temp, level + 1])
elif temp == 0:
return level + 1
大神解法:
class Solution:
# isSquare 为新增
def isSquare(self, n: int) -> bool:
sq = int(n ** 0.5)
return sq * sq == n
def numSquares(self, n: int) -> int:
####### 参考题解 用数学方法 拉格朗日四平方和定理######
################# python 动态规划超时 ##############
if self.isSquare(n):
return 1
while n & 3 == 0:
n >>= 2
if n & 7 == 7:
return 4 # 满足 4^a (8b+7) 返回 4
for i in range(1, int(n ** 0.5)+1):
if self.isSquare(n - i*i):
return 2
return 3