Leetcode: Perfect Squares
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.
1 public class Solution { 2 public int numSquares(int n) { 3 int[] dp = new int[n+1]; 4 Arrays.fill(dp, Integer.MAX_VALUE); 5 dp[0] = 0; 6 for (int i=1; i<=n; i++) { 7 int sqrt = (int)Math.sqrt(i); 8 for (int j=1; j<=sqrt; j++) { 9 dp[i] = Math.min(dp[i], dp[i-j*j]+1); 10 } 11 } 12 return dp[n]; 13 } 14 }