完全平方数(Python)
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
解题思路
需要累加的完全平方数为从1开始到比n小的最大平方数,遍历他们的和组合,找到最快的路径。注意:为了避免重复,累加时不要加上比自己小的完全平方数。
代码实现
from collections import deque
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
maxIndex=int(pow(n,0.5)) # 完全平方数根的最大值
indexList=list(range(1,maxIndex+1)) # 完全平方数
numSet=deque()
step=1
for index in indexList:
numSet.append((pow(index,2),index)) # 将完全平方数与其平方根保存至队列
if n==pow(int(pow(n,0.5)),2): # 若该数为完全平方数,直接输出1
return 1
while True:
step=step+1
length=len(numSet)
for iLength in range(length):
num,root=numSet.popleft()
for iIndex in range(root,maxIndex+1):
if pow(iIndex,2) + num == n:
return step
else:
numSet.append((pow(iIndex,2)+num,iIndex))