# Solution For Perfect Squares

The Perfect Squares problem on LeetCode is a popular dynamic programming problem in which we are given a positive integer n and are supposed to find the least number of perfect square numbers that sum up to n. In simpler terms, we need to find out the minimum number of perfect squares whose sum is equal to the given number n.

For example, if the input is 12, the output should be 3 because 12 can be represented as 4 + 4 + 4 or 9 + 1 + 1 + 1. In either case, we need a minimum of 3 perfect squares to represent 12.

To solve this problem, we need to come up with a dynamic programming approach. In this approach, we will maintain a 1D array dp, where dp[i] represents the minimum number of perfect squares required to sum up to i. We can use the following recurrence relation to compute the value of dp[i]:

dp[i] = min(dp[i – j*j] + 1) for j in [1, sqrt(i)]

In simpler terms, we can calculate dp[i] by iterating over all the possible perfect squares jj (where j belongs to [1, sqrt(i)]) and compute dp[i – jj] + 1. We take the minimum of all the computed values and assign it to dp[i].

The base case for this problem is dp[0] = 0 because we need 0 perfect squares to sum up to 0.

Here’s a step-by-step solution for the problem:

Step 1: Define the function that takes the input n and returns the minimum number of perfect squares that sum up to n.

Step 2: Create an array dp of size (n+1) and initialize all its values to infinity, except for dp[0] which should be set to 0.

Step 3: Iterate over all the integers i from 1 to n.

Step 4: Iterate over all the possible perfect squares j*j (where j belongs to [1, sqrt(i)]).

Step 5: For each jj, compute dp[i – jj] + 1 and assign the minimum of all such values to dp[i].

Step 6: Return dp[n] as the minimum number of perfect squares that sum up to n.

Here’s the Python code implementation of the above solution:

“`
import math

class Solution:
def numSquares(self, n: int) -> int:
dp = [float(‘inf’)] * (n+1)
dp[0] = 0

``````    for i in range(1, n+1):
for j in range(1, int(math.sqrt(i))+1):
dp[i] = min(dp[i], dp[i - j*j] + 1)

return dp[n]
``````

“`

The time complexity of this solution is O(n*sqrt(n)) because we are iterating over n integers and sqrt(n) perfect squares for each integer. The space complexity is O(n) because we are maintaining a 1D array of size (n+1).

Overall, the Perfect Squares problem on LeetCode can be solved using dynamic programming with a time complexity of O(n*sqrt(n)) and space complexity of O(n).

## Step by Step Implementation For Perfect Squares

```class Solution {
public int numSquares(int n) {
//Create an array of integers to store the minimum number of perfect squares needed to sum up to that integer
int[] dp = new int[n+1];
//Initialize the first element in the array to be 0 since it takes 0 perfect squares to sum up to 0
dp[0] = 0;
//Loop through the array starting from the second element
for(int i=1; i<=n; i++){
//Initialize the minimum number of perfect squares needed to sum up to the current integer to be the maximum integer value
dp[i] = Integer.MAX_VALUE;
//Loop through all the integers less than the current integer
for(int j=1; j*j<=i; j++){
//If the current integer is equal to the sum of a perfect square and another integer, update the minimum number of perfect squares needed
if(i == j*j){
dp[i] = 1;
}
//Otherwise, update the minimum number of perfect squares needed if it is less than the current value
else{
dp[i] = Math.min(dp[i], dp[i-j*j] + 1);
}
}
}
//Return the minimum number of perfect squares needed to sum up to the given integer
return dp[n];
}
}```
```class Solution:
def numSquares(self, n: int) -> int:
#Create an array of squares up to n
squares = [i**2 for i in range(1, int(n**0.5)+1)]

#Create an array of the minimum number of squares needed to sum to n for each n
#Start by assuming the minimum number of squares needed is n (the maximum possible)
min_squares = [n] * (n+1)
#The minimum number of squares needed to sum to 0 is 0
min_squares[0] = 0

#Loop through each value from 1 to n
for i in range(1, n+1):
#Loop through each square less than or equal to i
for square in squares:
#If the current square is greater than the current value, break
if square > i:
break
#Otherwise, update the minimum number of squares needed for the current value
#by taking the minimum of the current value or the minimum number of squares needed
#for the current value minus the current square plus 1 (the current square plus
#the minimum number of squares needed to sum to the difference between the current
#value and the current square)
min_squares[i] = min(min_squares[i], min_squares[i-square] + 1)

#Return the minimum number of squares needed to sum to n
return min_squares[n]```
```var numSquares = function(n) {

//Create an array to store the minimum number of perfect squares for each number from 1 to n
let dp = new Array(n+1).fill(Infinity);

//The minimum number of perfect squares for 1 is 1
dp[1] = 1;

//We can iterate through each number from 1 to n and update the array with the minimum number of perfect squares needed to make that number
for(let i = 1; i <= n; i++){
//We can iterate through each number up to i and see if it's a perfect square
for(let j = 1; j*j <= i; j++){
//If it is a perfect square, we update the array at index i with the minimum of the current value or 1 plus the minimum perfect squares needed to make i-j*j
if(j*j === i){
dp[i] = 1;
}else{
dp[i] = Math.min(dp[i], 1 + dp[i-j*j]);
}
}
}

//After we finish iterating, the minimum perfect squares needed to make n will be at the end of the array
return dp[n];

};```
```There are a few different ways to solve this problem. One way is to use a dynamic programming approach, where we keep track of the minimum number of squares needed to sum up to each number from 1 to n. We can then use this information to calculate the minimum number of squares needed to sum up to n.

Another way to solve this problem is to use a greedy approach. We can start by finding the largest perfect square that is less than or equal to n. We can then subtract this square from n, and repeat the process until n is 0. The number of squares needed will be the number of times we repeat this process.```
```public class Solution {
public int NumSquares(int n) {
// Create a dynamic programming array to store the
// minimum number of squares needed to sum to each
// value from 1 to n.
int[] dp = new int[n+1];

// Base case: The minimum number of squares needed
// to sum to 0 is 0.
dp[0] = 0;

// Iterate through each value from 1 to n.
for (int i = 1; i <= n; i++) {
// The minimum number of squares needed to sum
// to i is the minimum of the following:
// 1. The minimum number of squares needed to
//    sum to i - 1 plus 1 square (for the ith
//    value).
// 2. The minimum number of squares needed to
//    sum to the largest perfect square less
//    than or equal to i plus 1 square (for
//    the perfect square).
dp[i] = dp[i-1] + 1;
for (int j = 1; j * j <= i; j++) {
dp[i] = Math.Min(dp[i], dp[i - j*j] + 1);
}
}

// The minimum number of squares needed to sum to n
// is stored in dp[n].
return dp[n];
}
}```

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]