44 * 546. Remove Boxes
55 *
66 * 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.
1010
1111 Example 1:
1212 Input:
@@ -22,25 +22,39 @@ Each time you can choose some continuous boxes with the same color (composed of
2222 ----> [1, 1] (3*3=9 points)
2323 ----> [] (2*2=4 points)
2424 Note: The number of boxes n would not exceed 100.
25+
2526 */
27+
2628public 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+ */
2837 public int removeBoxes (int [] boxes ) {
2938 int [][][] dp = new int [100 ][100 ][100 ];
3039 return calculatePoints (boxes , dp , 0 , boxes .length - 1 , 0 );
3140 }
3241
3342 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+ }
3649 while (r > l && boxes [r ] == boxes [r - 1 ]) {
3750 r --;
3851 k ++;
3952 }
4053 dp [l ][r ][k ] = calculatePoints (boxes , dp , l , r - 1 , 0 ) + (k + 1 ) * (k + 1 );
4154 for (int i = l ; i < r ; i ++) {
4255 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 ));
4458 }
4559 }
4660 return dp [l ][r ][k ];
0 commit comments