File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ // A dynamic programming based JAVA program to find minimum
2
+ // number of squares whose sum is equal to a given number
3
+ class squares
4
+ {
5
+ // Returns count of minimum squares that sum to n
6
+ static int getMinSquares(int n)
7
+ {
8
+ // Create a dynamic programming table
9
+ // to store sq
10
+ int dp[] = new int[n+1];
11
+
12
+ // getMinSquares table for base case entries
13
+ dp[0] = 0;
14
+ dp[1] = 1;
15
+ dp[2] = 2;
16
+ dp[3] = 3;
17
+
18
+ // getMinSquares rest of the table using recursive
19
+ // formula
20
+ for (int i = 4; i <= n; i++)
21
+ {
22
+ // max value is i as i can always be represented
23
+ // as 1*1 + 1*1 + ...
24
+ dp[i] = i;
25
+
26
+ // Go through all smaller numbers to
27
+ // to recursively find minimum
28
+ for (int x = 1; x <= i; x++) {
29
+ int temp = x*x;
30
+ if (temp > i)
31
+ break;
32
+ else dp[i] = Math.min(dp[i], 1+dp[i-temp]);
33
+ }
34
+ }
35
+
36
+ // Store result and free dp[]
37
+ int res = dp[n];
38
+
39
+ return res;
40
+ }
41
+ public static void main(String args[])
42
+ {
43
+ System.out.println(getMinSquares(6));
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments