题干
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
最短路径->BFS
public class Perfect_square_number
{
public int numSquares(int n)
{
Queue<Vector<Integer>> queue = new LinkedList<Vector<Integer>>();
Vector<Integer>vector=new Vector<>();
vector.add(n);
vector.add(0);
queue.offer(vector);
boolean visited[] = new boolean[n+1];
visited[n] = true;
while (!queue.isEmpty())
{
Vector<Integer> v=queue.poll();
int number=v.get(0);
int step=v.get(1);
int i = 1;
int tNum = number - i*i;
while(tNum >= 0)//减去所有比n小的平方和得到m,存入[m,step],如13第一遍减去1*1,2*2,3*3,得到[12,1],[9,1],[4,1]
{
if (tNum == 0)
return step + 1;
if(!visited[tNum])
{
vector=new Vector<>();
vector.add(tNum);
vector.add(step+1);
queue.offer(vector);
visited[tNum] = true;
}
i += 1;
tNum = number - i*i;
}
}
return -1;
}
但是这个解法不是最优的解法,最优的解法使用的是四平方和定理。
四平方定理: 任何一个正整数都可以表示成不超过四个整数的平方之和。
那么我们这个问题的解法就变得很简单了,我们的结果只有1,2,3,4,四种可能。
另外还有一个非常重要的推论
满足四数平方和定理的数n(这里要满足由四个数构成,小于四个不行),必定满足 n=4a(8b+7)
根据这个重要的推论,我们可以非常迅速的写出这样的代码。
我们首先将输入的n迅速缩小。然后我们再判断,这个缩小后的数是否可以通过两个平方数的和或一个平方数组成,不能的话我们返回3,能的话我们返回平方数的个数。
现在我们的问题已经缩减到了,怎么判断一个数是由一个还是由两个平方数的和构成?对于这个问题,我们当然可以暴力破解。
//leetcode上最快的解法
class Solution
{
//贪心算法不适用
//e.g. 12 = 9+1+1+1 输出的是4 错误答案
//“最小” -> 想到最短路径 -> bfs算法 但这不是最优!
// public int numSquares(int n) {
// Queue<Integer[]> queue = new LinkedList<>();
// queue.offer(new Integer[] { 0, 0 });// 保存当前元素和已经用了的步数
// boolean[] visited = new boolean[n + 1];
// visited[0] = true;
// //bfs
// while (!queue.isEmpty()) {
// Integer[] cur = queue.poll();
// int num = cur[0];
// int step = cur[1];
// int i = 1;
// int tNum = num + i * i;
// while (tNum <= n) {//从 0->n 搜索不重复的和,一旦重复说明出现过,例如1+9=9+1=10,就不再添加
// if (tNum == n)
// return step + 1;
// if (!visited[tNum]) {
// queue.offer(new Integer[] { tNum, step + 1 });
// visited[tNum] = true;
// }
// i += 1;
// tNum = num + i * i;
// }
// }
// return 0;
// }
//Lagrange 四平方定理: 任何一个正整数都可以表示成不超过四个整数的平方之和。
//结果只有1,2,3,4,四种可能。
//推论:满足四数平方和定理的数n(必须满足由四个数构成),必定满足 n=4^a*(8^b+7)
public int numSquares(int n)
{
while (n % 4 == 0)
{
n /= 4;
}
if (n % 8 == 7) // 满足推论 说明由4个完全平方数构成
return 4;
int a = 0;
while (a * a <= n)
{
// 判断这个缩小后的数是否可以通过两个平方数的和或一个平方数组成
int b = (int) (Math.sqrt((n - a * a)));// 如果n=a^2 那么b=0
// if (a * a == n)
// return 1;
if (a * a + b * b == n)
//返回 a、b中非0的个数和
return (a != 0 ? 1 : 0) + (b != 0 ? 1 : 0);
a += 1;
}
return 3;
}
}