Very straightforward C++ DP solution


  • 15
    S

    For each i , the max # of perfect square is always i (when square = 1*1). So the boundary of each dp[i] = i.

    class Solution {
    public:
        int numSquares(int n) {
            if (n == 0) return 0;
            
            vector<int> dp(n+1, 0);
            
            for (int i=0; i<=n; ++i) {
                dp[i] = i;
                for (int j = 2; j<=sqrt(i); ++j) {
                    dp[i] = min(dp[i], 1 + dp[i - j*j]);
                }
            }
            
            return dp[n];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.