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

[LeetCode] Perfect Squares

时间:2015-11-06 21:05:22      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

解题思路

动态规划法。初始化时令dp[i * i] = 1,状态转移方程为dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);

实现代码

C++:

// Runtime: 544 ms
class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, 0x7fffffff);
        for (int i = 0; i * i <= n; i++)
        {
            dp[i * i] = 1;
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; i + j * j <= n; j++)
            {
                dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);
            }
        }

        return dp[n];
    }
};

Java:

// Runtime: 69 ms
public class Solution {
    public int numSquares(int n) {
        int dp[] = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        for (int i = 1; i * i <= n; i++) {
            dp[i * i] = 1;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; i + j * j <= n; j++) {
                dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]);
            }
        }

        return dp[n];
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

[LeetCode] Perfect Squares

标签:

原文地址:http://blog.csdn.net/foreverling/article/details/49686415

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