LeetCode #279 - Perfect Squares - Medium

Problem

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

Example

given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Algorithm

整理一下題意:給定一個正整數n,要求找到一組平方數使得其加起來的和等於n且這組數的個數最少,返回這組數的個數。

使用動態規劃的思路解決。設f(i)表示i對應平方數組合最小個數,則f(i)必然等於最小的f[i-平方數]再加一,即狀態轉移方程爲

f[i]=min(f[i-squ[j])+1;

於是f(n)即爲解。

代碼如下。

class Solution {
public:
    int numSquares(int n) {
        vector<int> f(n+1,0);
        f[1]=1;
        for(int i=2;i<n+1;i++){
            int min=INT_MAX;
            for(int j=1;j<=sqrt(n);j++){
                if(i-j*j>=0&&min>f[i-j*j]) min=f[i-j*j];
            }
            f[i]=min+1;
        }
        return f[n];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章