leetcode学习笔记(完全平方数,BFS)
题目描述
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
思路:
显然本题使用bfs,一层一层的遍历。但是如果不加限制条件必定超时;
所以每次需要增加判断条件:
1.超过n,直接跳过;
2.如果当前结果之前出现过,跳过。
如下图:
代码如下:
class Solution {
public int numSquares(int n) {
if(n==1) return 1;
int[] flag=new int[n];
int[] f=new int[n];
Queue<Integer> queue=new LinkedList<>();
int size=1;
for(;;size++){
if(size*size>n) break;
f[size]=size*size;
flag[n-f[size]]=1;
queue.offer(n-f[size]);
}
int depth=1;
while(true){
int ssize=queue.size();
for(int i=0;i<ssize;i++){
int cur=queue.poll();
if(cur<0) continue;
if(cur==0) return depth;
for(int j=1;j<size;j++){
int ss=cur-f[j];
if(ss>=0) {
if(flag[ss]==0)
queue.offer(ss);
flag[ss]=1;
}
}
}
depth++;
}
}
}