题目描述
题目来源于leetcode:https://leetcode-cn.com/explore/learn/card/queue-stack/217/queue-and-bfs/874/
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
分析
这道题比打开转盘锁要简单很多,我们输入的数字n当作根节点,把n和一个完全平方数的差作为子节点,进行层序遍历,直到遍历得到的节点也是一个完全平方数,就结束了,只需要输出层数即可。在每一层的末尾添加一个-1,当遍历得到的结果为-1是,说明要进入下一层了,此时执行result++。
代码
class Solution {
/*
* 判断是否为完全平方数
*
*/
public static Boolean judge(int n) {
int b = (int) Math.sqrt(n);
return b*b == n;
}
/*
* 得到一个数与小于它的完全平方数的差
*
*/
public static List<Integer> action(int n){
List<Integer> list = new ArrayList<>();
for(int i=n;i>=0;i--) {
if(judge(i)==true) {
list.add(n-i);
}
}
return list;
}
public int numSquares(int n) {
int result = 1;
Queue<Integer> queue = new LinkedList<>();
if(judge(n)==true) {//如果这个数本身就是完全平方数,直接返回1
return 1;
}
queue.add(n);
queue.add(-1);
while(queue.isEmpty()==false) {
int a = queue.poll();
if(a==-1) {
result++;
if(queue.peek()!=-1)
queue.offer(-1);//为每一层的末尾添加-1
}else if(judge(a)==true){//找到节点为完全平方数,返回result
return result;
}else {
for(int b : action(a)) {//把 数与小于它的完全平方数的差 作为根节点加入队列中
int c = b;
queue.add(c);
}
}
}
return -1;
}
}