[leetcode] 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.

分析:DP问题,设dp[n]为输入正整数n时,函数返回的结果。找规律如下:

dp[0] = 0

dp[1] = 1
dp[2] = 2
dp[3] = 3

dp[4] = 1 = dp[0] + 1 = dp[4-2*2] + 1

dp[5] = 2
dp[6] = 3
dp[7] = 4

dp[8] = 2 = dp[4] + 1 = dp[8-2*2] + 1

dp[9] = 1 = dp[0] + 1 = dp[9-3*3] + 1

代码如下:

    public int numSquares(int n) {
        int[] dp = new int[n+1];
        dp[0] = 0;
        for(int i = 1; i <= n; i++) {
            dp[i] = dp[i-1]+1;
            for(int j = 2; j*j <= i; j++) {
                dp[i] = Math.min(dp[i], dp[i-j*j]+1);
            }
        }
        return dp[n];
    }

 

posted @ 2015-12-13 09:35  lasclocker  阅读(152)  评论(0编辑  收藏  举报