Friday, January 31, 2020

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.
Example 1:
Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.


class Solution {
public:
    int numSquares(int n) {
        // recursion done with one for loop.
        if (n < 4) {
            return n;
        }
        // Dynamic
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3;
       
        for (int i = 4; i <= n; i++) {
            if (dp[i] == INT_MAX) {
                for (int j = 1; j <= sqrt(i); j++) {
                    dp[i] = min(dp[i], dp[i - j*j] + 1);
                }
            }
        }
        return dp[n];
    }
};

==================== Efficient one ==========

int numSquares(int n) { int dp[n+1]; dp[0] = 0; dp[1] = 1; for(int i=2; i<=n; i++){ dp[i]=i; for(int j=1; j*j<=i; j++){ int x = dp[i-j*j]+1; dp[i]= min(dp[i],x); } } return dp[n]; }

No comments:

Post a Comment