您的位置:首页 > Web前端

[leetcode-279]Perfect Squares(java)

2015-09-25 08:16 363 查看
问题描述:

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.

分析:这道题并没有想出来,看到网上提到动态规划算法时,还在想这题怎么动态规划,后来才知道确实是动态规划,对于要求的当前节点而言都是从前面的节点转移过来的,只是这些转移节点并非一个,而是多个,比如1*1,2*2,3*3,,,那么相应的res[i-1]、res[i-4]、res[i-9]等等都是转移点。从这些候选项中找到最小的那个,然后加1即可。

代码如下:280ms

[code]public class Solution {
    public int numSquares(int n) {
        int[] res = new int[n+1];
        res[0] = 0;

        for(int i = 1;i<=n;i++){
            int minNum = Integer.MAX_VALUE;

            for(int base = 1;i-base*base>=0;base++){
                if(res[i-base*base]<minNum)
                    minNum = res[i-base*base];
            }
            res[i] = minNum+1;
        }
        return res
;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: