leetcode 279.完全平方数

106 阅读1分钟

279.完全平方数

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

输入: n = 13
输出: 2
解释: 13 = 4 + 9.
from queue import Queue


class Solution:
    def numSquares(self, n: int) -> int:
        around = []
        for i in range(1, n + 1):
            if i ** 2 <= n:
                around.append(i ** 2)
            else:
                break;

        r = 0
        visited = set()  # 防止重复运算
        # ----------------BFS 开始----------------------
        # 初始化根节点
        q = Queue()
        q.put((0, r))
        # 进入队列循环
        while not q.empty():
            # 取出一个元素
            cur, step = q.get()
            step += 1
            # 放入周围元素
            for a in around:
                a += cur
                if a == n:
                    return step
                if a < n and (a, step) not in visited:
                    visited.add((a, step))
                    q.put((a, step))
        # ----------------------------------------------
        return 0
# BFS将当前数字的总和视为节点,加上一个完全平方数后能达到的数字作为一阶邻域,
# 搜索到达 n 的最短路径