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];
    }
}


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

Perfect Squares 费马小定理求乘法逆元k=b^(p-2)

Problem Description A number x is called a perfect square if there exists an integer b satisfying x...
  • Big_Rui
  • Big_Rui
  • 2017年07月24日 15:36
  • 143

LeetCode——Perfect Squares

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

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

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

leetcode_279. Perfect Squares

leetcode_279. Perfect Squares

leetcode谷歌面试题279. Perfect Squares

无权图广搜谷歌面试题

279. Perfect Squares

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

【LeetCode从零单刷】Perfect Squares

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

DP (7) -- Ones and Zeroes, Longest Increasing Subsequence, Perfect Squares

Ones and Zeroes,Longest Increasing Subsequence,Guess Number Higher or Lower II
  • dwt0317
  • dwt0317
  • 2017年01月11日 14:55
  • 113

[LeetCode] 279. Perfect Squares 解题报告

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, ...
  • a921122
  • a921122
  • 2017年02月19日 03:04
  • 149

leetcode--Perfect Squares

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 1...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Perfect Squares
举报原因:
原因补充:

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