[LeetCode]Perfect Squares

題目鏈接: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.


題目解法:

最初看到這個題,我想到的是回溯法,剪了半天的枝還是各種超時,後來參考了xudli的解法,才知道這道題用動態規劃更合適。

我們設d[i]=a表示數字i對應的least number of perfect square numbers爲a,則顯然d[1]=1爲初始條件,接着我們用揹包問題的思想,對於i從2到n,嘗試向其中放入perfect square number j,j從1開始枚舉,每次放入後得到的結果爲d[i - j*j]+1,也就是在不放入j的least number基礎上+1得到d[i]的最小值,對於不同的j,我們應該選取其中最小的那個,也就是說:d[i] = min{d[i-j*j],j=1,2,3...,j*j<=i}。

最後,d[n]就是結果。

代碼如下:

class Solution {
public:
    int getMin(int a, int b){
        return a < b ? a : b;
    }
    int numSquares(int n) {
        int *d = new int[n+1];
        d[1] = 1; // d[i]表示數字i的Prefect Seuares值。
        for(int i = 2; i <= n; i++){
            int j = 1;
            int min = 99999999;
            while(j*j <= i){
                if(j*j == i){
                    min = 1;
                    break;
                }
                min = getMin(min,d[i-j*j] + 1);
                j++;
            }
            d[i] = min;
        }
        return d[n];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章