The Indian Engineer

Problem 279 Perfect Squares

Posted on 5 mins

Math Dynamic-Programming Breadth-First Search

Problem Statement

Link - Problem 279

Question

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

Constraints:

Solution

class Solution {
public:
    vector<int> dp;

    int numSquares(int n) {
        // Initialize the dp array with INT_MAX except for dp[0] which is 0
        dp.resize(n + 1, INT_MAX);
        dp[0] = 0; // Set dp[0] to 0

        // Call the solve function to recursively calculate the minimum number of squares
        return solve(n);
    }

    int solve(int n) {
        // If n is 0, it can be formed using 0 squares
        if (n == 0)
            return 0;
        // If n is negative, it cannot be formed, return INT_MAX
        if (n < 0)
            return INT_MAX;
        // If the result for n is already calculated, return it
        if (dp[n] != INT_MAX)
            return dp[n];

        int ans = INT_MAX;
        // Iterate through all numbers from 1 to sqrt(n)
        for (int i = 1; i * i <= n; i++) {
            // Recursively calculate the minimum number of squares needed for n-i*i
            int subproblem = solve(n - i * i);
            // Update the answer with the minimum of current answer and subproblem + 1
            ans = min(ans, subproblem + 1);
        }
        // Memoize the result for n
        dp[n] = ans;
        // Return the minimum number of squares needed for n
        return ans;
    }
};

Complexity Analysis

| Algorithm                    | Time Complexity | Space Complexity |
| ---------------------------- | --------------- | ---------------- |
| Memoized Dynamic Programming | O(n sqrt(n))    | O(n)             |

Explanation

Intial Thoughts

This problem involves breaking down a number into sums of perfect squares, a classic concept in number theory. My initial thoughts are to relate this problem to known results or patterns in number theory. I’m reminded of the concept of sum of squares functions, Lagrange’s Four-Square Theorem, and the Legendre’s Three-Square Theorem. Another approach could be using a dynamic programming approach to build up the solution iteratively.

Intuitive Analysis

To solve this problem intuitively, we can think of it as a dynamic programming problem where each number n can be broken down into its ‘components’ of perfect squares. We can iteratively build up the solution by trying all possible combinations of perfect squares that sum up to n. As in many dynamic programming problems, memoization will be key to prevent redundant calculations and speed up the solution process. The key insight here is to realize that for a given number n, trying all possible ‘subproblems’ of n is inefficient, and we should only try ‘subproblems’ that are perfect squares themselves.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Count Primes https://leetcode.com/problems/count-primes Medium
Ugly Number II https://leetcode.com/problems/ugly-number-ii Medium
Ways to Express an Integer as Sum of Powers https://leetcode.com/problems/ways-to-express-an-integer-as-sum-of-powers Medium