379. 完全平方数 BFS
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
- BFS:以队列的形式依次寻找满足的平方数
from collections import deque
# BFS
class Solution:
def numSquares(self, n: int) -> int:
queue = deque()
visited = set()
queue.append((n, 0))
while queue:
num, step = queue.popleft()
targets = [num - i * i for i in range(1, int(num ** 0.5) + 1)]
for target in targets:
if target == 0:
return step + 1
if target not in visited:
visited.add(target)
queue.append((target, step + 1))