码迷,mamicode.com
首页 > 其他好文 > 详细

513. Perfect Squares

时间:2019-01-16 15:33:26      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:ret   square   positive   ram   sqrt   mat   integer   min   bec   

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

标签:ret   square   positive   ram   sqrt   mat   integer   min   bec   

原文地址:https://www.cnblogs.com/lawrenceSeattle/p/10277118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!