标签:
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 int k = 1; 5 for (int i=1; i<=n; i++) { 6 if (i == k*k) { 7 dp[i] = 1; 8 k++; 9 } 10 else dp[i] = i; 11 } 12 for (int i=2; i<=n; i++) { 13 int sqrt = (int)Math.sqrt(i); 14 for (int j=1; j<=sqrt; j++) { 15 dp[i] = Math.min(dp[i], dp[i-j*j]+1); 16 } 17 } 18 return dp[n]; 19 } 20 }
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5077413.html