Skip to content

Commit 515e7af

Browse files
authored
Update Perfect Squares.java
1 parent 4645f74 commit 515e7af

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

Medium/Perfect Squares.java

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,15 @@
11
class Solution {
2-
Set<Integer> squareNums;
32
public int numSquares(int n) {
4-
squareNums = new HashSet<>();
5-
for (int i = 1; i * i <= n; i++) {
6-
squareNums.add(i * i);
7-
}
8-
int count = 1;
9-
for (count = 1; count <= n; count++) {
10-
if (isDividedBy(n, count)) {
11-
return count;
12-
}
13-
}
14-
return count;
15-
}
16-
17-
private boolean isDividedBy(int n, int count) {
18-
if (count == 1) {
19-
return squareNums.contains(n);
20-
}
21-
for (Integer squareNum : squareNums) {
22-
if (isDividedBy(n - squareNum, count - 1)) {
23-
return true;
3+
int[] dp = new int[n + 1];
4+
Arrays.fill(dp, Integer.MAX_VALUE);
5+
dp[0] = 0;
6+
for(int i = 1; i <= n; i++) {
7+
int min = Integer.MAX_VALUE;
8+
for (int j = 1; i - j * j >= 0; j++) {
9+
min = Math.min(min, dp[i - j * j] + 1);
2410
}
11+
dp[i] = min;
2512
}
26-
return false;
13+
return dp[n];
2714
}
2815
}

0 commit comments

Comments
 (0)