279. 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.

Hide Similar Problems
 (E) Count Primes (M) Ugly Number II
 
Easy to understand DP solution:
public class Solution {
    public int numSquares(int n) {
        if(n<=3)
            return n;
        
        int[] results = new int[n+1];
        results[0] = 0;
        results[1] = 1;
        results[2] = 2;
        results[3] = 3;
        return numSquares(results, n);
    }
    
    private int numSquares(int[] results, int n) {
        if(results[n] > 0)
            return results[n];
            
        int root = (int)Math.sqrt(n);
        int rootSqure = root*root;
        if(rootSqure == n)
        {
            results[n] = 1;
            return 1;
        }
        
        results[n] = Integer.MAX_VALUE;
        for(int i = root; i>= 2; --i)
        {
            int square = i*i;
            results[n] = Math.min(results[n], 
            numSquares(results, square) + numSquares(results, n-square));
        }
        return results[n];
    }
}

 

posted @ 2016-07-11 13:47  新一代的天皇巨星  阅读(197)  评论(0)    收藏  举报