您的位置:首页 > Web前端

leetcode Perfect Squares

2016-07-22 21:44 585 查看
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.

经典dp题目,dp题目最重要的是找状态转移方程,https://segmentfault.com/a/1190000003768736讲的非常清楚,这道题是为了找构成整数所需的最小个数的平方数,可以理解为若n=a+b*b,那么n所需的最小平方数个数为a所需的最小平方数个数+1,如果能想到这里这道题基本就解决了,我们只需要找到小于等于n的所有平方数,将他们的初值设为1,然后进行比较即可,代码:

public int numSquares(int n) {
int[] res=new int[n+1];
Arrays.fill(res,Integer.MAX_VALUE);
for(int i=0;i*i<=n;i++){
res[i*i]=1;
}
for(int a=0;a<=n;a++){
for(int b=0;a+b*b<=n;b++){
res[a+b*b]=Math.min(res[a]+1,res[a+b*b]);
}
}
return res
;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法