Perfect Squares

原创 2016年08月29日 11:16:32

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.

思路:dp,我写的是recursion + memorization版本;其实这题就类似于coin change。只不过,coin change的问题,是固定的硬币,现在这个是小于n的所有可能的平方数的解。like: n = 10, coin 就是1,4,9.

此题用的是沁园老师的recursion + memorization的解法。自己写出来的,很开心。

public class Solution {
    public int numSquares(int n) {
        if(n<=0) return -1;
        int[] dp = new int[n+1];
        Arrays.fill(dp,-1);
        calculate(n, dp);
        return dp[n];
    }
    
    public int calculate(int n, int[] dp) {
        if(n<=0) return 0;
        if(dp[n] != -1){
            return dp[n];
        }
        
        int val = Integer.MAX_VALUE;
        for(int i=1; i<=Math.sqrt(n); i++){
            val = Math.min(val, calculate(n-i*i, dp) + 1);
        }
        dp[n] = val;
        return dp[n];
    }
}


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

相关文章推荐

LeetCode——Perfect Squares

题目描述: 将数字n,分解成k个平方数之和。如12 = 4 + 4 + 4,13 = 9 + 4。求k的最小值。         题目解法: 初读题目,发现如果n本身就是平方数最完美不过了,这样...

279. Perfect Squares

279. Perfect Squares Given a positive integer n, find the least number of perfect square numbers (...

279. Perfect Squares-Leetcode(关于DP的再深入研究)

先上题目: Given a positive integer n, find the least number of perfect square numbers (for example, 1,...

279. Perfect Squares

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

leetcode_279. Perfect Squares

leetcode_279. Perfect Squares

leetcode谷歌面试题279. Perfect Squares

无权图广搜谷歌面试题

LeetCode 279. Perfect Squares 转换思维图的无权BFS,寻最短路径

Perfect Squares 题意 注意 思路 代码 题外memset的使用279. Perfect Squares Given a positive integer n, find the l...

leetcode 279 : Perfect Squares

1、原题如下 Given a positive integer n, find the least number of perfect square numbers (for example, 1,...

hdu 3524 Perfect Squares(找规律,循环节,快速幂取模)

Perfect Squares Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)...

279. Perfect Squares

题意: Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)