-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeast No Sum Of Perfect Squares which will give N
More file actions
45 lines (40 loc) · 1.21 KB
/
Copy pathLeast No Sum Of Perfect Squares which will give N
File metadata and controls
45 lines (40 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// A dynamic programming based JAVA program to find minimum
// number of squares whose sum is equal to a given number
class squares
{
// Returns count of minimum squares that sum to n
static int getMinSquares(int n)
{
// Create a dynamic programming table
// to store sq
int dp[] = new int[n+1];
// getMinSquares table for base case entries
dp[0] = 0;
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
// getMinSquares rest of the table using recursive
// formula
for (int i = 4; i <= n; i++)
{
// max value is i as i can always be represented
// as 1*1 + 1*1 + ...
dp[i] = i;
// Go through all smaller numbers to
// to recursively find minimum
for (int x = 1; x <= i; x++) {
int temp = x*x;
if (temp > i)
break;
else dp[i] = Math.min(dp[i], 1+dp[i-temp]);
}
}
// Store result and free dp[]
int res = dp[n];
return res;
}
public static void main(String args[])
{
System.out.println(getMinSquares(6));
}
}