279. Perfect Squares
2016-05-03 本文已影响61人
小明与小明
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
int numSquares(int n) {
if(n <= 2){
return n;
}
int min = n, temp = 0;
for( int i = 2; i * i <= n; i++){
if(n % (i * i) == 0){
temp = n / (i * i);
}else{
temp = n / (i * i) + numSquares(n % (i * i));
}
if(temp < min){
min = temp;
}
}
return min;
}