# leetcode-279-完全平方数-java

package pid279;
/*  Perfect Squares

*/
public class main {

public static void main(String[] args) {
int[] testTable = {12,13,25,34};
for (int i=0;i<testTable.length;i++) {
test(testTable[i]);
}
}

private static void test(int ito) {
Solution solution = new Solution();
int rtn;
long begin = System.currentTimeMillis();
System.out.print(ito+" ");
System.out.println();
rtn = solution.numSquares(ito);//执行程序
long end = System.currentTimeMillis();
System.out.print(rtn+" ");
System.out.println();
System.out.println("耗时：" + (end - begin) + "ms");
System.out.println("-------------------");
}

}


dp[i] = MIN(dp[i], dp[i - j] + 1)

因为遍历了之前所有的情况，所以速度很慢

package pid279;

public class Solution {
public int numSquares(int n) {
if(n==1){
return 1;
}
int[] dp=new int[n+1];
dp[0]=Integer.MAX_VALUE;
int i=1;
while(i*i<=n){
dp[i*i]=1;
i++;
}
if(dp[n]==1){
return 1;
}
for(i=2;i<=n;i++){
if(dp[i]==1){
continue;
}
int min=Integer.MAX_VALUE;
for(int j=1;j<=i/2+1;j++){
if(dp[j]+dp[i-j]<min){
min=dp[j]+dp[i-j];
}
}
dp[i]=min;
}

return dp[n];
}

}


class Solution {
public int numSquares(int n) {
int[] dp = new int[n + 1]; // 默认初始化值都为0
for (int i = 1; i <= n; i++) {
dp[i] = i; // 最坏的情况就是每次+1
for (int j = 1; i - j * j >= 0; j++) {
dp[i] = Math.min(dp[i], dp[i - j * j] + 1); // 动态转移方程
}
}
return dp[n];
}
}



©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客