2017.9.5
有了动态规划的思路之后,这道以前看起来没啥思路的题,也有了思路。
做的很快,很开心。
dp【n】 = min { dp【n】,dp【j】+ dp【n-j】}
public class Solution {
/**
* @param n a positive integer
* @return an integer
*/
public static int numSquares(int n) {
// Write your code here
int []res = new int[n+1];
for(int i = 1; i <= n; i++){
res[i] = i;
int tmp = (int)Math.sqrt(i);
if(tmp*tmp == i){
res[i] = 1;
}
}
for(int i = 1; i <= n; i++){
for(int j = i/2 + 1; j >=1; j--){
if(res[i] > res[j] + res[i-j]){
res[i] = res[j] + res[i-j];
}
}
}
return res[n];
}
}