-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSolution279.java
37 lines (30 loc) · 866 Bytes
/
Solution279.java
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
package dynamic_problem;
import java.util.ArrayList;
import java.util.List;
public class Solution279 {
public int numSquare(int n) {
List<Integer> squareList = generateSquareList(n);
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int min = Integer.MAX_VALUE;
for (int square:squareList) {
if (i >= square) {
min = Math.max(min, dp[i - square] + 1);
}
}
dp[i] = min;
}
return dp[n];
}
private List<Integer> generateSquareList(int n) {
List<Integer> squareList = new ArrayList<>();
int square = 1;
int diff = 3;
while (square <= n) {
squareList.add(square);
square += diff;
diff += 2;
}
return squareList;
}
}