leetcode@ [279]Perfect Squares

https://leetcode.com/problems/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.

class Solution {
public:
    int getMaximumSquare(int n){
        int ret = (int)sqrt(n);
        return ret;
    }
    int dfs(int load, vector<int> &dp){
        if(dp[load]) return dp[load];
        if(load == 0){
            return 0;
        }
        
        int next = getMaximumSquare(load);
        int Min = numeric_limits<int>::max();
        for(int v=next;v>=1;v--){
            if(load-v*v >= 0){
                Min = min(Min, dfs(load-v*v, dp));
            } 
        }
        dp[load] = Min + 1;
        return dp[load];
    }
    int numSquares(int n) {
        vector<int> dp(n+1);
        for(int i=0;i<dp.size();++i) dp[i] = 0;
        
        dp[n] = dfs(n, dp);
        return dp[n];
    }
};
 
原文地址:https://www.cnblogs.com/fu11211129/p/4930018.html