给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...
)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n =12
输出: 3 解释:12 = 4 + 4 + 4.
示例 2:
输入: n =13
输出: 2 解释:13 = 4 + 9.
解题思路:将n拆成两个平方和,当无法满足时候,拆成一个平方和一个非平方的和。将非平方放入队列,等待下一轮的拆解。
public int numSquares(int n) {
int count=0;
Queue<Integer> q=new LinkedList<>();
if(isSqrt(n)) {//n是平方和
return 1;
}
q.offer(n);
while(!q.isEmpty()) {
int len=q.size();
for(int i=0;i<len;i++) {//得到当前层队列长度
int top=q.poll();
for(int j=1;j<=Math.sqrt(top);j++) {
int m=top-j*j;
if(isSqrt(m)) {//判断减去后的数是否是平方数
count=count+2;
return count;
}
//如果m不是平方数,放入队列中,等待下一轮的检测。
q.offer(m);
}
}
//当前层队列没有满足条件,下一层循环。
count++;
}
return count;
}
public static boolean isSqrt(int n) {
int sqrt = (int) Math.sqrt(n);
if(sqrt*sqrt==n) {
return true;
}
return false;
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int n = Integer.parseInt(line);
int ret = new 完全平方数().numSquares(n);
String out = String.valueOf(ret);
System.out.print(out);
}
}
感谢下面的参考链接的大佬: