Simple O(n^2) time with O(n) Space java solution


  • 0
    D
    public class Solution {
    public int numSquares(int n) {
        int[] numSquare = new int[n + 1];
        numSquare[0] = 0;
        numSquare[1] = 1;
        
        for (int i = 2; i < n + 1; i++) {
            numSquare[i] = Integer.MAX_VALUE;
            for (int x = 1; x * x <= i; x++) {
                numSquare[i] = Math.min(numSquare[i], numSquare[i - x * x]);
            }
            numSquare[i] += 1;
        }
        return numSquare[n];
    }
    

    }


  • 0
    T

    I think you can initialize to numSquare[i] = i as well, because 1+1+....+1 is always the worst solution for any number.


Log in to reply
 

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