forked from algorithm009-class01/algorithm009-class01
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumSquares.java
More file actions
30 lines (25 loc) · 687 Bytes
/
NumSquares.java
File metadata and controls
30 lines (25 loc) · 687 Bytes
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
package dynamic;
import java.util.Arrays;
public class NumSquares {
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) {
int min = Integer.MAX_VALUE;
int j = 1;
while (i - j*j >= 0){
min = Math.min(min,dp[i - j*j] + 1);
++j;
}
dp[i] = min;
}
return dp[n];
}
public static void main(String[] args) {
int n = 12;
NumSquares numSquares = new NumSquares();
int r = numSquares.numSquares(n);
System.out.println(r);
}
}