1.题目描述
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:输入: n = 13
输出: 2
解释: 13 = 4 + 9.
2.解题思路
参考链接:https://leetcode-cn.com/problems/perfect-squares/solution/dong-tai-gui-hua-bfs-zhu-xing-jie-shi-python3-by-2/
3.代码实现
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
q = [n]
vis = set()
step = 0
while q:
l =len(q)
step += 1
for _ in range(l):
tmp = q.pop(0)
for i in range(1,int(tmp ** 0.5)+1):
x = tmp - i*i
if x == 0:
return step
if x not in vis:
vis.add(x)
q.append(x)