-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetCodeQ279Tabulation.java
More file actions
51 lines (46 loc) · 1.41 KB
/
leetCodeQ279Tabulation.java
File metadata and controls
51 lines (46 loc) · 1.41 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
46
47
48
49
50
51
package DynamicProgramming;
public class leetCodeQ279Tabulation {
public static boolean isPerfect(int n) {
int sqrt = (int) (Math.sqrt(n));
return (sqrt * sqrt == n);
}
// Tabulation TC = O(n*n) It will be submited .
public static int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (isPerfect(i))
dp[i] = 1;
else {
int min = Integer.MAX_VALUE;
for (int j = 1; j * j <= i/2; j++) {
int count = dp[j * j] + dp[i - j * j];
min = Math.min(min, count);
}
dp[i] = min;
}
}
return dp[n];
}
// Tabulation TC = O(n* root n)
public static int numSquares1(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (isPerfect(i))
dp[i] = 1;
else {
int min = Integer.MAX_VALUE;
for (int j = 1; j * j <= i; j++) {
int count = dp[j * j] + dp[i - j * j];
min = Math.min(min, count);
}
dp[i] = min;
}
}
return dp[n];
}
public static void main(String[] args) {
int n = 3461 ;
System.out.println(numSquares(n));
System.out.println(numSquares1(n));
}
}