-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumSquares.java
More file actions
32 lines (30 loc) · 763 Bytes
/
NumSquares.java
File metadata and controls
32 lines (30 loc) · 763 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
31
32
import java.util.ArrayList;
import java.util.Arrays;
/**
* @description:
* @Author: JachinDo
* @Date: 2019/10/28 14:26
*/
public class NumSquares {
public int numSquares(int n) {
int[] dp = new int[n+1];
dp[0] = 0;
dp[1] = 1;
boolean flag = false;
for (int i = 2; i < n+1; i++) {
flag = false;
int min = Integer.MAX_VALUE;
for (int j = 1; j*j <= i; j++) {
if (j * j == i + 1) {
dp[i] = 1;
flag = true;
break;
} else {
min = Math.min(min,dp[i-j*j] + 1);
}
}
dp[i] = flag ? dp[i] : min;
}
return dp[n];
}
}