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], 于是時(shí)間復(fù)雜度為O(n^2).這樣會(huì)出現(xiàn)嚴(yán)重超時(shí)。
如果只檢查完全平方數(shù)的dp,會(huì)讓時(shí)間復(fù)雜度降到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];
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,927評論 0 33
  • Given a positive integer n, find the least number of perf...
    matrxyz閱讀 214評論 0 0
  • 先來發(fā)一張朋友圈獲贊比較多的畫,其實(shí)不過是二十分鐘的團(tuán)練速寫。可能大多數(shù)人還是停留在欣賞是否畫得像的層面上。 而畫...
    步搖閱讀 914評論 7 11
  • 趁早創(chuàng)始人王瀟-瀟灑姐說,塑造靈魂和鍛煉肉體是生活雙引擎,也是最能印證時(shí)間看得見的兩件事。深以為然,我今年也開始全...
    Nina姐閱讀 865評論 0 4
  • BigScreenStudio 是一款大屏幕內(nèi)容布局編輯與控制的一體化解決方案,支持常用內(nèi)容和多種可視化組件,直觀...
    大表哥001閱讀 2,624評論 0 1

友情鏈接更多精彩內(nèi)容