|
3 | 3 | // 本题测试链接 : https://leetcode.com/problems/remove-boxes/ |
4 | 4 | public class Code02_RemoveBoxes { |
5 | 5 |
|
6 | | -public static int removeBoxes(int[] boxes) { |
| 6 | +public static int removeBoxes1(int[] boxes) { |
7 | 7 | int N = boxes.length; |
8 | 8 | 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); |
10 | 10 | return ans; |
11 | 11 | } |
12 | 12 |
|
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) { |
14 | 14 | if (L > R) { |
15 | 15 | return 0; |
16 | 16 | } |
17 | 17 | if (dp[L][R][K] > 0) { |
18 | 18 | return dp[L][R][K]; |
19 | 19 | } |
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); |
21 | 21 | for (int i = L + 1; i <= R; i++) { |
22 | 22 | 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)); |
24 | 54 | } |
25 | 55 | } |
26 | 56 | dp[L][R][K] = ans; |
|
0 commit comments