513. Perfect Squares

Posted lawrenceseattle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了513. 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.

Example
Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9
public class Solution {
    /**
     * @param n: a positive integer
     * @return: An integer
     */
    public int numSquares(int n) {
        if(n <= 1) return n;
        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 1;
        for(int i = 2; i <= n; i++) {
            dp[i] = Integer.MAX_VALUE;
        }
        
        for(int i = 2; i <= n; i++) {
            if(isSquare(i)) {
                dp[i] = 1;
            }
            for(int j = 1; j < i; j++) {
                if(isSquare(j)) {
                    dp[j] = 1;
                }
                dp[i] = Math.min(dp[i], dp[j] + dp[i-j]);
            }
        }
        return dp[n];
    }
    
    public boolean isSquare(int n) {
        double m = Math.floor(Math.sqrt((double)n)+0.5);
        return m * m == (double)n;
    }

}

以上是关于513. Perfect Squares的主要内容,如果未能解决你的问题,请参考以下文章

Perfect Squares

279. Perfect Squares

*Perfect Squares

279. Perfect Squares

279. Perfect Squares

279. Perfect Squares