题目描述
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
题解
思路一:
根据四平方定理:任何一个正整数都可以表示成不超过四个整数的平方之和。 推论:满足四数平方和定理的数n(四个整数的情况),必定满足 n=4^a(8b+7),很简单就能判断
class Solution {
public int numSquares(int n) {
if(n <= 0){return 0;}
if(check1(n)){
return 1;
}else if(check2(n)){
return 2;
}else if(check3(n)){
return 3;
}else{
return 4;
}
}
public boolean check1(int n){
int tem = (int)Math.sqrt(n);
return tem*tem == n;
}
public boolean check2(int n){
for(int i = 1 ; i * i < n ; i++){
if(check1(n-i*i))
return true;
}
return false;
}
public boolean check3(int n){
for(int i = 1 ; i * i < n ; i++){
if(check2(n-i*i)){
return true;
}
}
return false;
}
}
思路二:
使用队列
public int numSquares(int n) {
boolean[] visited = new boolean[n+1];
Queue<Integer> queue = new LinkedList<>();
queue.offer(n);
int level = 1, size = 1;
while (!queue.isEmpty()) {
size--;
int num = queue.poll();
for (int i = 1; num - i * i >= 0; i++) {
int rest = num - i * i;
if (rest == 0) return level;
if (!visited[rest]) queue.offer(rest);
visited[rest] = true;
}
if (size == 0) {
size = queue.size();
level++;
}
}
return 0;
}