279. Perfect Squares
- Total Accepted: 66852
- Total Submissions: 188029
- Difficulty: Medium
- Contributors: Admin
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.
Subscribe to see which companies asked this question.
Show Similar Problems
public class Solution{
public int numSquares(int n){
int[] dp=new int[n+1];
Arrays.fill(dp,Integer.MAX_VALUE);
for(int i=0;i*i<=n;i++)
dp[i*i]=1;
for(int a=0;a<=n;a++){
for(int b=0;a+b*b<=n;b++){
dp[a+b*b]=Math.min(dp[a]+1,dp[a+b*b]);
}
}
return dp[n];
}
}