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[n]=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[n]; } }