Skip to content

Commit 07b1377

Browse files
committed
modify code
1 parent 1e1be96 commit 07b1377

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

src/class46/Code02_RemoveBoxes.java

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,54 @@
33
// 本题测试链接 : https://leetcode.com/problems/remove-boxes/
44
public class Code02_RemoveBoxes {
55

6-
public static int removeBoxes(int[] boxes) {
6+
public static int removeBoxes1(int[] boxes) {
77
int N = boxes.length;
88
int[][][] dp = new int[N][N][N];
9-
int ans = process(boxes, 0, N - 1, 0, dp);
9+
int ans = process1(boxes, 0, N - 1, 0, dp);
1010
return ans;
1111
}
1212

13-
public static int process(int[] boxes, int L, int R, int K, int[][][] dp) {
13+
public static int process1(int[] boxes, int L, int R, int K, int[][][] dp) {
1414
if (L > R) {
1515
return 0;
1616
}
1717
if (dp[L][R][K] > 0) {
1818
return dp[L][R][K];
1919
}
20-
int ans = process(boxes, L + 1, R, 0, dp) + (K + 1) * (K + 1);
20+
int ans = process1(boxes, L + 1, R, 0, dp) + (K + 1) * (K + 1);
2121
for (int i = L + 1; i <= R; i++) {
2222
if (boxes[i] == boxes[L]) {
23-
ans = Math.max(ans, process(boxes, L + 1, i - 1, 0, dp) + process(boxes, i, R, K + 1, dp));
23+
ans = Math.max(ans, process1(boxes, L + 1, i - 1, 0, dp) + process1(boxes, i, R, K + 1, dp));
24+
}
25+
}
26+
dp[L][R][K] = ans;
27+
return ans;
28+
}
29+
30+
public static int removeBoxes2(int[] boxes) {
31+
int N = boxes.length;
32+
int[][][] dp = new int[N][N][N];
33+
int ans = process2(boxes, 0, N - 1, 0, dp);
34+
return ans;
35+
}
36+
37+
public static int process2(int[] boxes, int L, int R, int K, int[][][] dp) {
38+
if (L > R) {
39+
return K * K;
40+
}
41+
if (dp[L][R][K] > 0) {
42+
return dp[L][R][K];
43+
}
44+
int ans = 0;
45+
int last = L;
46+
while (last + 1 <= R && boxes[last + 1] == boxes[L]) {
47+
last++;
48+
}
49+
int pre = K + last - L;
50+
ans = (pre + 1) * (pre + 1) + process2(boxes, last + 1, R, 0, dp);
51+
for (int i = last + 2; i <= R; i++) {
52+
if (boxes[i] == boxes[L] && boxes[i - 1] != boxes[L]) {
53+
ans = Math.max(ans, process2(boxes, last + 1, i - 1, 0, dp) + process2(boxes, i, R, pre + 1, dp));
2454
}
2555
}
2656
dp[L][R][K] = ans;

0 commit comments

Comments
 (0)