1. 程式人生 > 其它 >LeetCode 279 Perfect Squares DP

LeetCode 279 Perfect Squares DP

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not

Solution

顯然設 \(dp[i]\)

表示數字 i 的最少切分數,考慮轉移的時候需要列舉此時的數字劃分,由於其中一個數一定是平方數,所以只需要 \(O(\sqrt{n})\) 的複雜度即可

點選檢視程式碼
class Solution {
private:
    int dp[10005];
    bool check(int x){
        if(((int)sqrt(x)*(int)sqrt(x))==x)return true;
        return false;
    }
public:
    int numSquares(int n) {
        if(n==1)return 1;
        dp[1] = 1;
        for(int i=2;i<=n;i++){
            dp[i] = 9999999;
            if(check(i))dp[i] = 1;
            else{
                for(int j=1;j<=sqrt(i);j++)dp[i] = min(dp[i], dp[j*j]+dp[i-j*j]);
            }
        }
        return dp[n];
    }
};