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.
Analysis:
A DP solution like the Coin Changes.
Solution:
1 public class Solution { 2 public int numSquares(int n) { 3 int[] nums = new int[n+1]; 4 5 for (int i=1;i<=n;i++){ 6 nums[i] = Integer.MAX_VALUE; 7 for (int j=1;j*j<=i;j++){ 8 nums[i] = Math.min(nums[i], nums[i-j*j]+1); 9 } 10 } 11 return nums[n]; 12 } 13 }