给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, …)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
思路: 感觉算是一道动态规划题,可以利用自下向上的备忘录方法进行解答,创建一个长度为 n 的数组,将各个数的结果存储在对应的下标数组中。
假设 a[0] =0,
1 是由 a[0] +1
2 是由 a[1] + 1
3 是 a[2] + 1
4 是 a[0] +1 ,因为 4 可以被 4 整除。
那么类似的递推公式就是:a[i] = a[i-j*j] + 1;
class Solution {
public int numSquares(int n) {
int[] dp = new int[n+1];
Arrays.fill(dp,1000000);
a[0] = 0;
for(int i = 1;i <= n;i++){
int j = 1;
while(i - j*j >= 0){
dp[i] = Math.min(dp[i],dp[i-j*j]+1);
j++;
}
}
return dp[n];
}
}
大神用队列解题的代码:
class Solution {
public int numSquares(int n) {
Queue<Integer> queue = new LinkedList<>();
queue.add(n);
int step = 0;
//定义一个访问标志数组
//广度优先遍历求无权图的最短路径时,如果当前要访问的节点已经别访问过了,说明访问当前节点是在这次访问之前发生的
//由于是在这次访问之前发生的,所以之前访问的路径长度一定是小于等于这次访问的,所以这次的访问就没有任何意义
//这次的访问就被取消
boolean[] visited = new boolean[n+1];
while(!queue.isEmpty()){
int len = queue.size();
//把每步能到达的所有的点都走了
for(int j=0;j<len;j++){
int num = queue.poll();
for(int i=1;num-i*i>=0;i++){
int k = num-i*i;
if(k==0){
return step+1;
}
//判断当前位置是否已经被访问过
if(!visited[k]){
queue.add(k);
visited[k] = true;
}
}
}
step++;
}
return step;
}
}