279. Perfect Squares java solutions

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.

 1 public class Solution {
 2     public int numSquares(int n) {
 3         if(n < 1) return 0;
 4         int jend = (int)Math.sqrt(n);
 5         int[] dp = new int[n+1];
 6         Arrays.fill(dp,n+1);
 7         dp[0] = 0;
 8         for(int i = 1 ; i <= n; i++){
 9             for(int j = 1; j <= i; j++){
10                 if(j*j <= i)
11                     dp[i] = Math.min(dp[i],dp[i-j*j] + 1);
12             }
13         }
14         return dp[n];
15     }
16 }

该题和

322. Coin Change java solutions

几乎是一样的,下标的处理和判断即可。

posted @ 2016-07-01 15:54  Miller1991  阅读(144)  评论(0编辑  收藏  举报