LeetCode 279: Perfect Squares Solution

Master LeetCode problem 279 (Perfect Squares), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can use dynamic programming. We will iterate from 1 to n and for each number i, we will try to find the minimum number of perfect squares that sum up to i. We can do this by considering all possible perfect squares less than or equal to i and finding the minimum among their corresponding sums.

For example, to find the minimum number of perfect squares that sum up to 12:

  • For i = 1, we cannot form 12 using only perfect squares, so we skip.
  • For i = 2, we cannot form 12 using only perfect squares, so we skip.
  • For i = 3, we cannot form 12 using only perfect squares, so we skip.
  • For i = 4, we can form 12 by adding 4 three times (4 + 4 + 4), so the answer is 3.
  • For i = 5, we consider all possible perfect squares less than 5 which is 4. So, 5 can be formed by adding 1 (5 = 1 + 4) perfect square, so the answer is 2.

We repeat this process for all numbers from 1 to n to find the minimum number of perfect squares required to sum up to n.

Solution Code

public int numSquares(int n) {
    int[] dp = new int[n+1];
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j*j <= i; j++) {
            dp[i] = Math.min(dp[i], dp[i - j*j] + 1);
        }
    }
    
    return dp[n];
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 279 (Perfect Squares)?

This page provides optimized solutions for LeetCode problem 279 (Perfect Squares) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 279 (Perfect Squares)?

The time complexity for LeetCode 279 (Perfect Squares) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 279 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 279 in Java, C++, or Python.

Back to LeetCode Solutions