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.
题意
给定一个正数,寻找完美平方数之和等于这个正数并且使其完美平方数的个数最少
分析
用一个命名为num的数组来保存个数
1. n=1,因为1是完美平方数,所以n[1]=1
2. n=2,2=1+1,所以n[2]=2
3. n=3,3=2+1=1+1+1,所以n[3]=3
4. n=4,4=3+1或者4=4,取较小值,所以n[4]=1
5. …
n. n=n,n=min(num[n-i]+1),其中i为完美平方数
从上述流程可以看出,对于每个n,它的最小完美平方数的个数等于n-i时的最小完美平方数个数加1,所以需要用到动态规划,num的初始值是0。
实现
class Solution {
public int numSquares(int n) {
if(n<=0)
return 0;
int[] leastNum=new int[n+1];
Arrays.fill(leastNum,Integer.MAX_VALUE);
leastNum[0]=0;
for(int i=1;i<=n;++i)
{
for(int j=1;j*j<=i;++j)
{
leastNum[i]=Math.min(leastNum[i],leastNum[i-j*j]+1);
}
}
return leastNum[n];
}
}