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

【Leetcode】Perfect Squares

时间:2016-05-30 15:34:19      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/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.

思路:

 n=m^2+s
 m=(int)Math.sqrt(n) 向下取整 表最大可能的完全平方数 c[i]表示组成i需要的最少完全平方数的个数 递推公式:

c[i] =1+c[s] 考虑12=3^2+3 c[12]=1+c[3]=1+3=4, 但12=4+4+4 即c[12]=3
所以不是m为最大的平方数就一定能取得c[i]的,需要遍历 所有j<m n=j^2+k min(1+c[k])

算法

public int numSquares(int n) {  
    int c[] = new int[n + 1];  
    for (int i = 1; i <= n; i++) {  
        int tmp = (int) Math.sqrt(i);  
        c[i] = c[i - tmp * tmp] + 1;  
        for (int j = tmp - 1; j >= 1; j--) {  
            tmp = j * j;  
            c[i] = Math.min(c[i - tmp] + 1, c[i]);  
        }  
    }  
    return c[n];  
}  


【Leetcode】Perfect Squares

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51520494

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