您的位置:首页 > Web前端

Perfect Squares——Leetcode

2015-09-20 17:03 369 查看
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
.

题目大意:给一个正整数,找出可以由最少个平方数构成的数量是多少。

解题思路:dynamic programming,递推公式F
=min{F[n-1]+1,F[n-4]+2,F[n-9]+3,...};

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