4
4
* 546. Remove Boxes
5
5
*
6
6
* Given several boxes with different colors represented by different positive numbers.
7
- You may experience several rounds to remove boxes until there is no box left.
8
- Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k points.
9
- Find the maximum points you can get.
7
+ * You may experience several rounds to remove boxes until there is no box left.
8
+ * Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1), remove them and get k*k points.
9
+ * Find the maximum points you can get.
10
10
11
11
Example 1:
12
12
Input:
@@ -22,25 +22,39 @@ Each time you can choose some continuous boxes with the same color (composed of
22
22
----> [1, 1] (3*3=9 points)
23
23
----> [] (2*2=4 points)
24
24
Note: The number of boxes n would not exceed 100.
25
+
25
26
*/
27
+
26
28
public class _546 {
27
- /**credit: https://leetcode.com/articles/remove-boxes/#approach-2-using-dp-with-memorizationaccepted*/
29
+ /**
30
+ * credit: https://leetcode.com/articles/remove-boxes/#approach-2-using-dp-with-memorizationaccepted
31
+ *
32
+ * For an entry in dp[l][r][k], l represents the starting index of the subarray,
33
+ * r represents the ending index of the subarray
34
+ * and k represents the number of elements similar to the rth element
35
+ * following it which can be combined to obtain the point information to be stored in dp[l][r][k].
36
+ */
28
37
public int removeBoxes (int [] boxes ) {
29
38
int [][][] dp = new int [100 ][100 ][100 ];
30
39
return calculatePoints (boxes , dp , 0 , boxes .length - 1 , 0 );
31
40
}
32
41
33
42
public int calculatePoints (int [] boxes , int [][][] dp , int l , int r , int k ) {
34
- if (l > r ) return 0 ;
35
- if (dp [l ][r ][k ] != 0 ) return dp [l ][r ][k ];
43
+ if (l > r ) {
44
+ return 0 ;
45
+ }
46
+ if (dp [l ][r ][k ] != 0 ) {
47
+ return dp [l ][r ][k ];
48
+ }
36
49
while (r > l && boxes [r ] == boxes [r - 1 ]) {
37
50
r --;
38
51
k ++;
39
52
}
40
53
dp [l ][r ][k ] = calculatePoints (boxes , dp , l , r - 1 , 0 ) + (k + 1 ) * (k + 1 );
41
54
for (int i = l ; i < r ; i ++) {
42
55
if (boxes [i ] == boxes [r ]) {
43
- dp [l ][r ][k ] = Math .max (dp [l ][r ][k ], calculatePoints (boxes , dp , l , i , k + 1 ) + calculatePoints (boxes , dp , i + 1 , r - 1 , 0 ));
56
+ dp [l ][r ][k ] = Math .max (dp [l ][r ][k ],
57
+ calculatePoints (boxes , dp , l , i , k + 1 ) + calculatePoints (boxes , dp , i + 1 , r - 1 , 0 ));
44
58
}
45
59
}
46
60
return dp [l ][r ][k ];
0 commit comments