279. 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.

一刷
题解:
dynamic programming:
dp[n] = 1+min(dp[n-1], dp[n-4], ..., dp[n-root*root])
root = int(sort(n))

time complexity O(n^2), space complexity O(n)

public class Solution {
    public int numSquares(int n) {
        int root = new Double(Math.sqrt(n)).intValue();
        int[] dp = new int[n+1];
        for(int i=1;i<=root; i++){
            dp[i*i] = 1;
        }
        
        for(int i=1; i<=n; i++){
            int min = Integer.MAX_VALUE;
            int i_root = new Double(Math.sqrt(i)).intValue();
            for(int j=1; j<=i_root; j++){
                min = Math.min(min, 1+dp[i-j*j]);
            }
            dp[i] = min;
        }
        return dp[n];
    }
}

二刷
最开始想到的思路是,dp[n] = dp[i] + dp[n-i], 于是时间复杂度为O(n^2).这样会出现严重超时。
如果只检查完全平方数的dp,会让时间复杂度降到O(n*sqrt(n)).
dp[n] = 1 + dp[n-root^2]

public class Solution {
    public int numSquares(int n) {
        if(n<=0) return 0; 
        int[] dp = new int[n+1];
        int root = new Double(Math.sqrt(n)).intValue();
        for(int i=1; i<=root; i++){
            dp[i*i] = 1;
        }
        
        for(int i=2; i<=n; i++){
            int min = Integer.MAX_VALUE;
            int i_root = new Double(Math.sqrt(i)).intValue();
            for(int j=1; j<=i_root; j++){
                min = Math.min(1 + dp[i-j*j], min);
            }
            dp[i] = min;
        }
        
        return dp[n];
    }
}

三刷
DP

class Solution {
    public int numSquares(int n) {
        int[] dp = new int[n+1];
        for(int i=1; i*i<=n; i++){
            dp[i*i] = 1;
        }
        
      
        for(int i=2; i<=n; i++){
            int min = Integer.MAX_VALUE;
            int root = (int)Math.sqrt(i);
            for(int j=1; j<=root; j++){
               min = Math.min(min, 1 + dp[i-j*j]);
            }
            dp[i] = min;
        }
        return dp[n];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,766评论 0 33
  • Given a positive integer n, find the least number of perf...
    matrxyz阅读 182评论 0 0
  • 先来发一张朋友圈获赞比较多的画,其实不过是二十分钟的团练速写。可能大多数人还是停留在欣赏是否画得像的层面上。 而画...
    步摇阅读 871评论 7 11
  • 趁早创始人王潇-潇洒姐说,塑造灵魂和锻炼肉体是生活双引擎,也是最能印证时间看得见的两件事。深以为然,我今年也开始全...
    Nina姐阅读 753评论 0 4
  • BigScreenStudio 是一款大屏幕内容布局编辑与控制的一体化解决方案,支持常用内容和多种可视化组件,直观...
    大表哥001阅读 2,492评论 0 1