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.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:其实这道题和青蛙跳台阶的那一道也有点相似。用f(i)表示当n为i的时候,最少的完全平方数的个数。f(i)就等于f(i-1)+f(1) 、f(i-4)+f(4)、f(i-9)+f(9)、、、f(i-k)+f(k),(其中k要小于i) 中最小的一个加上1。其中f(1)、f(4)和f(9)等均为1。那么就反过来求,求f(1)、f(2)、、、,f(n)自然也会有结果了。
public class Solution {
public int numSquares(int n) {
if(n<=0) return -1;
int[] nums=new int[n+1];
int c=1;
while(c*c<=n)
{
nums[c*c]=1;
c++;
}
for(int i=1;i<=n;i++)
{
if(nums[i]==1) continue;
int min=Integer.MAX_VALUE;
int j=1;
while(j*j<i)
{
min=min < (nums[i-j*j]+1) ? min : nums[i-j*j]+1;
j++;
}
nums[i]=min;
}
return nums[n];
}
}