资讯专栏INFORMATION COLUMN

[LeetCode] 279. Perfect Squares

mist14 / 2745人阅读

Problem

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Solution
class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n+1];
        Arrays.fill(dp, n+2);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            int min = dp[i];
            int factor = 1;
            while (i-factor*factor >= 0) {
                min = Math.min(min, dp[i-factor*factor]+1);
                factor++;
            }
            dp[i] = min;
        }
        return dp[n];
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72622.html

相关文章

  • leetcode279. Perfect Squares

    摘要:题目要求判断一个数字最少由几个平方数的和构成。思路一暴力递归要想知道什么样的组合最好,暴力比较所有的结果就好啦。当然,效率奇差。代码如下思路三数学统治一切这里涉及了一个叫做四平方定理的内容。有兴趣的可以去了解一下这个定理。 题目要求 Given a positive integer n, find the least number of perfect square numbers (...

    reclay 评论0 收藏0
  • LeetCode 279: Perfect Squares

    摘要:题目给一个正整数问他最少能被几个完全平方数和表示。举例,返回,返回解法我能看懂的就只有的方法,原理如下代码 题目: 给一个正整数n,问他最少能被几个完全平方数和表示。 举例: 13=4+9, 返回2;12 = 4+4+4, 返回3; 解法: 我能看懂的就只有dynamic-programming的方法,原理如下: dp[0] = 0 dp[1] = dp[0]+1 = 1 dp[2...

    codecook 评论0 收藏0
  • [Leetcode] Perfect Squares 完美平方数

    摘要:动态规划复杂度时间空间思路如果一个数可以表示为一个任意数加上一个平方数,也就是,那么能组成这个数最少的平方数个数,就是能组成最少的平方数个数加上因为已经是平方数了。 Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4...

    Moxmi 评论0 收藏0
  • [LintCode/LeetCode] Perfect Squares

    摘要:动态规划法建立空数组从到每个数包含最少平方数情况,先所有值为将到范围内所有平方数的值赋两次循环更新,当它本身为平方数时,简化动态规划法四平方和定理法 Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) whi...

    sydMobile 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<