其他分享
首页 > 其他分享> > 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];
    }
};

标签:Perfect,perfect,square,return,int,sqrt,integer,279,Squares
来源: https://www.cnblogs.com/xinyu04/p/16265243.html