美文网首页
279. Perfect Squares

279. Perfect Squares

作者: 小明与小明 | 来源:发表于2016-05-03 23:21 被阅读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;

}

相关文章

网友评论

      本文标题:279. Perfect Squares

      本文链接:https://www.haomeiwen.com/subject/rddrrttx.html