Simple Java Solution


  • 0
    A
    public class Solution {
        public int numSquares(int n) {
            int[] result = new int[n + 1];
            
            result[1] = 1;
            // All perfect squares can be reached in one step
            for (int i = 1; i * i <= n; i++) {
                result[i * i] = 1;
            }
            
            for (int i = 2; i <= n; i++) {
                if (result[i] == 0) {
                    int min = Integer.MAX_VALUE;
                    // Iterate through half of each number between 2 and n
                    for (int j = i - 1; j >= i / 2; j--) {
                        if (result[j] + result[i - j] < min) {
                            min = result[j] + result[i - j];
                        }
                    }
                    result[i] = min;
                }
            }
            
            return result[n];
        }
    }

Log in to reply
 

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