[leetcode] PerfectSquares

PerfectSquares

  • 問題描述:首先定義完美數字是{1, 4, 9, 16 … , n^2}.然後給定一個整數N,試計算N最少由幾個完美數字求和得到。比如12=4+4+4,13=4+9
  • 分析:
    • 對於一個數字N,它所能選擇的最大完美數字就是int(sqrt(N))^2=X。
    • 所以對於N的結果他可以由min{N-{1,4,…,X}} + 1構造得到。
    • 所以該題是一個動態規劃的題目。
    • dp[0] = 0;
    • dp[1] = 1;
    • dp[i] = min{dp[i-j]} + 1 for j in {1, j*j<=i}
    • 時間複雜度應該是O(NN0.5)=O(N1.5)O(N*N^{0.5})=O(N^{1.5})
  • 代碼
//
// Created by 樑棟 on 2019-05-16.
//
#include <cmath>
#include <iostream>
using namespace std;
class Solution {
public:
    int numSquares(int n) {
        int dp[n + 1];
        memset(dp, 0, sizeof(dp));
        dp[0] = 0; // 0
        dp[1] = 1; // 1
        for(int i=2;i<=n;i++){
            int x = (int) sqrt(i);
            int cur_res = n;
            // 代表所能使用的所有perfect number
            for(int y=1;y<=x;y++){
                // 計算所有能用的perfect number 之間的最小值
                cur_res = min(cur_res, dp[i - y * y]);
            }
            dp[i] = cur_res + 1;
            cout<<(i)<<", "<<dp[i]<<endl;
        }
        return dp[n];
    }
    static void solution(){
        Solution solution1;
        cout<<solution1.numSquares(13)<<endl;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章