279. 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.

简单的一道DP题目。

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n+1,INT_MAX-1);//这里如果不是MAX-1,下面+1的时候就会溢出
        for(int i=1;i*i<=n;i++){
            dp[i*i]=1;
        }
        for(int i=1;i<=n;i++){
            for(int j=0;j*j<=i;j++){
                dp[i]=min(dp[i-j*j]+1,dp[i]);
            }
        }
        return dp[n];
    }
};

你可能感兴趣的:(279. Perfect Squares)