LeetCode 0279. Perfect Squares完全平方数【Medium】【Python】【BFS】
Problem
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
问题
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
思路
解法一
BFS
把每个整数都看成图中的节点,如果两个整数之差为一个平方数,表示两点之间存在一条边连通。
求最小平方数,就是求 n 到 0 的最短路径,于是就可以用 BFS。
时间复杂度: O(n^2)
空间复杂度: O(n^2)
Python3代码
class Solution:</