- 给定一个整数,求由几个完全平方数相加及平方数是多少
例:输入:13 输出:[9 4] 2 13 = 9 + 4 = 3^2 + 2^2
思路如下:
采用队列
来遍历层次搜索树,并定义内部类存储key、Sq、step三个值。
1)找到key=0
,确定正确路径:13=9+....
。返回9
以及最深的树高2
,表示13
可以由step
个完全平方数组成。
2)在main函数中将9
add进入ArrayList里,重复获取13-9
的最大平方数。
3)打印结果。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class MySqrt {
/**
* 定义函数getSqrt 返回整数n的最大开方数的根
* 例:13 = 9 +4 最大平方数9 返回根号9 = `3`
* 使用牛顿迭代法求整数n的开方
* @param n
* @return
*/
public static int getSqrt(int n){
double X0 = n;
double Y0;
Y0= X0*X0 - n;
while (Math.abs(Y0)>0.0001){
X0 = X0 - Y0/(2*X0);
Y0 = X0*X0 - n;
}
return (int) X0;
}
/**
* 定义函数getNums 返回整数n中小于n的完全平方数
* 13-> [9 4 1]
* 12->[9 4 1]
* 4->[1]
* @param n
* @return
*/
public static int[] getNums(int n){
int size = MySqrt.getSqrt(n);
int[] nums = new int[size];
for (int i = 1; i <= size; i++) {
nums[i-1] = i*i;
}
return nums;
}
/**
* 定义内部类
* key n与完全平方数之差
* Sq 完全平方数
* step 树高
*/
static class Ele{
int key ;
int Sq;
int step;
public Ele(int key,int Sq, int step){
this.key = key;
this.Sq = Sq;
this.step = step;
}
@Override
public String toString() {
return this.key+" "+this.Sq+" "+this.step;
}
}
/**
* 方法返回正确路径的最大平方数
* @param n
* @return
*/
public static int getMaxSq(int n){
int[] nums ;
int LuJing = 1;
int finallyNum = 0;
ArrayList<Ele> arrayList = new ArrayList<>();
Queue<Ele> queue = new LinkedList<Ele>();
Ele ele = new Ele(n,0,0);
arrayList.add(ele);
while (ele!=null){
if (ele.key==0){
finallyNum = ele.step;
break;
}
nums = getNums(ele.key);
for (int i = 0; i <nums.length; i++) {
queue.offer(new Ele(ele.key - nums[i],nums[i],ele.step+1));
}
ele = queue.poll();
}
//System.out.println(ele.toString());
return ele.Sq;
}
public static void main(String[] args) {
//System.out.println(Arrays.toString(getNums(13)));
int n = 13;
int temp = 0;
ArrayList arrayList = new ArrayList();
//System.out.println(getMaxSq(n));
/*
在找到n的最大平方数之后做差
之后不断的重复这一过程,直到差为0
*/
while (n>=0){
if(n==0){
break;
}
temp = getMaxSq(n);
arrayList.add(temp);
n = n - temp;
}
System.out.println(arrayList.toString());
System.out.println("The MaxSq's size is "+arrayList.size());
}
}
结果:
[9, 4]
The MaxSq's size is 2
Process finished with exit code 0