Question

Formatted question description: https://leetcode.ca/all/279.html

 279	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.

 @tag-dp

Algorithm

Create a one-dimensional dp array of length n+1, initialize the first value to 0, and initialize the remaining values to INT_MAX

i loops from 0 to n, j loops from 1 to the position of i+jj <= n, and then updates the value of dp[i+jj] each time, dynamically updating the dp array, where dp[i] means positive The integer i can be composed of multiple perfect squares.

Note that the wording here, i must start from 0, j must start from 1. Because our original intention is to use dp[i] to update dp[i + j * j], if i=0, j=1 , Then dp[i] and dp[i + j * j] are equal.

Code

Java

  • import java.util.Arrays;
    
    public class Perfect_Squares {
    
        public static void main(String[] args) {
            Perfect_Squares out = new Perfect_Squares();
            Solution s = out.new Solution();
    
            System.out.println(s.numSquares(43));
        }
    
        class Solution_lessLoop {
            public int numSquares(int n) {
    
                if (n <= 0) {
                    return 0;
                }
    
                // count[i] means, for number i, minimum square count
                int[] dp = new int[n + 1];
                Arrays.fill(dp, Integer.MAX_VALUE);
    
                dp[0] = 0;
                for (int i = 0; i <= n; ++i) {
                    for (int j = 1; i + j * j <= n; ++j) {
                        dp[i + j * j] = Math.min(dp[i + j * j], dp[i] + 1);
                    }
                }
    
                return dp[n];
            }
        }
    
        class Solution {
            public int numSquares(int n) {
    
                if (n <= 0) {
                    return 0;
                }
    
                // count[i] means, for number i, minimum square count
                int[] count = new int[n + 1];
                Arrays.fill(count, Integer.MAX_VALUE);
                count[0] = 0;
    
                // fill in sqaures first
                int maxPossibleSqaureRoot = (int)Math.sqrt(n * 1.0);
                for (int i = 1; i <= maxPossibleSqaureRoot; i++) {
                    count[(int)Math.pow(i, 2)] = 1;
                }
    
                for (int i = 1; i <= n; i++) {
    
                    int start = 0;
                    int end = i / 2;
    
                    for (int j = start; j <= end; j++) {
                        count[i] = Math.min(count[i], count[j] + count[i - j]);
                    }
                }
    
                return count[n];
            }
        }
    }
    
  • // OJ: https://leetcode.com/problems/perfect-squares/
    // Time: O(NS) where S is the count of square numbers less than n.
    // Space: O(N)
    class Solution {
    public:
        int numSquares(int n) {
            vector<int> v(n + 1, INT_MAX);
            for (int i = 1; i * i <= n; ++i) v[i * i] = 1;
            for (int i = 1; i <= n; ++i) {
                if (v[i] == 1) continue;
                for (int j = 1; j * j < i; ++j) {
                    v[i] = min(v[i], 1 + v[i - j * j]);
                }
            }
            return v[n];
        }
    };
    
  • class Solution(object):
      def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        squares = []
        j = 1
        while j * j <= n:
          squares.append(j * j)
          j += 1
        level = 0
        queue = [n]
        visited = [False] * (n + 1)
        while queue:
          level += 1
          temp = []
          for q in queue:
            for factor in squares:
              if q - factor == 0:
                return level
              if q - factor < 0:
                break
              if visited[q - factor]:
                continue
              temp.append(q - factor)
              visited[q - factor] = True
          queue = temp
        return level
    
    

All Problems

All Solutions