|
1 | 1 | package class46; |
2 | 2 |
|
| 3 | +// 本题测试链接 : https://leetcode.com/problems/remove-boxes/ |
3 | 4 | public class Code02_RemoveBoxes { |
4 | 5 |
|
5 | | -public int removeBoxes(int[] boxes) { |
| 6 | +public static int removeBoxes(int[] boxes) { |
6 | 7 | int N = boxes.length; |
7 | 8 | int[][][] dp = new int[N][N][N]; |
8 | | -return process(boxes, 0, N - 1, 0, dp); |
| 9 | +int ans = process(boxes, 0, N - 1, 0, dp); |
| 10 | +return ans; |
9 | 11 | } |
10 | 12 |
|
11 | | -// boxes[L....R],前面还跟着K个boxes[L] |
12 | | -// 前面的包袱和L...R所有的数都消掉,最好得分是什么 |
13 | 13 | public static int process(int[] boxes, int L, int R, int K, int[][][] dp) { |
14 | 14 | if (L > R) { |
15 | 15 | return 0; |
16 | 16 | } |
17 | | -if (dp[L][R][K] != 0) { |
18 | | -return dp[L][R][K]; |
19 | | -} |
20 | | -if (L == R) { |
21 | | -dp[L][R][K] = (K + 1) * (K + 1); |
| 17 | +if (dp[L][R][K] > 0) { |
22 | 18 | return dp[L][R][K]; |
23 | 19 | } |
24 | | -while (L < R && boxes[L] == boxes[L + 1]) { |
25 | | -L++; |
26 | | -K++; |
27 | | -} |
28 | | -int ans = (K + 1) * (K + 1) + process(boxes, L + 1, R, 0, dp); |
29 | | -for (int m = L + 1; m <= R; m++) { |
30 | | -if (boxes[L] == boxes[m]) { |
31 | | -ans = Math.max(ans, process(boxes, L + 1, m - 1, 0, dp) + process(boxes, m, R, K + 1, dp)); |
| 20 | +int ans = process(boxes, L, R - 1, 0, dp) + (K + 1) * (K + 1); |
| 21 | +for (int i = L; i < R; i++) { |
| 22 | +if (boxes[i] == boxes[R]) { |
| 23 | +ans = Math.max(ans, process(boxes, i + 1, R - 1, 0, dp) + process(boxes, L, i, K + 1, dp)); |
32 | 24 | } |
33 | 25 | } |
34 | 26 | dp[L][R][K] = ans; |
|
0 commit comments