题目:完全平方数
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例:
输入: n = 12,输出: 3
解释: 12 = 4 + 4 + 4.
输入: n = 13,输出: 2
解释: 13 = 4 + 9.
-------------------------------------------------------------------------------
解法1#:神奇的 "四平方和定理"
四平方和定理说明每个正整数均可表示为4个整数的平方和。它是费马多边形数定理和华林问题的特例。
class Solution2(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
while n % 4 == 0:
n /= 4
if n % 8 == 7:
return 4
num = 0
while num ** 2 <= n:
num2 = int((n - num ** 2) ** 0.5)
if num ** 2 + num2 ** 2 == n:
return (not not num) + (not not num2)
num += 1
return 3
解法2#:利用广度优先遍历的逻辑
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
q = []
# 创建队列
q.append([n, 0]) # [n,0] 代表当前节点的值和步数
temp = [False for _ in range(n+1)]
# 保存遍历过的结点
temp[n] = True
# 遍历队列里的节点
while any(q):
num, step = q.pop(0)
i = 1
left_num = num -i**2
while left_num >= 0:
# 最先达到0的一定是步数最少的
if left_num == 0:
return step+1
# 只添加没有遍历过的节点
if not temp[left_num]:
q.append((left_num,step+1))
temp[left_num] = True
i += 1
left_num = num - i**2
参考:
https://blog.csdn.net/wangsiyu34567/article/details/82825475