Given several boxes with different colors represented by different positive numbers.
You may experience several rounds to remove boxes until there is no box left. 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.
Find the maximum points you can get.
Example 1:
Input:
[1, 3, 2, 2, 2, 3, 4, 3, 1]
Output:
23
Explanation:
[1, 3, 2, 2, 2, 3, 4, 3, 1] ----> [1, 3, 3, 4, 3, 1] (3*3=9 points) ----> [1, 3, 3, 3, 1] (1*1=1 points) ----> [1, 1] (3*3=9 points) ----> [] (2*2=4 points)
Note: The number of boxes n
would not exceed 100.
思路:https://leetcode.com/problems/remove-boxes/discuss/101310/Java-top-down-and-bottom-up-DP-solutions
方法一:Top-down, 记忆化搜索
1 // top-down memorization dfs 2 class Solution { 3 public: 4 int removeBoxes(vector<int>& boxes) { 5 int len = boxes.size(); 6 int dp[100][100][100] = {0}; 7 return removeBoxes(boxes, dp, 0, len-1, 0); 8 } 9 private: 10 int removeBoxes(vector<int>& boxes,int dp[100][100][100],int i,int j,int k) { 11 if (i>j) { 12 return 0; 13 } 14 if (dp[i][j][k] > 0) { 15 return dp[i][j][k]; 16 } 17 for (; i + 1 <= j && boxes[i + 1] == boxes[i]; i++, k++); 18 int res = removeBoxes(boxes, dp, i + 1, j, 0) + (k + 1) * (k + 1); 19 for (int m = i + 1; m <= j; m++) { 20 if (boxes[m] == boxes[i]) { 21 res = max(res, removeBoxes(boxes, dp, i + 1, m - 1, 0) + removeBoxes(boxes, dp, m, j, k + 1)); 22 } 23 } 24 dp[i][j][k] = res; 25 return dp[i][j][k]; 26 } 27 };
方法二:bottom-up DP
1 class Solution { 2 public: 3 int removeBoxes(vector<int>& boxes) { 4 int len = boxes.size(); 5 int dp[100][100][100] = {0}; 6 for (int i = 0; i < len; i++) { 7 for (int k = 0; k <= i; k++) { 8 dp[i][i][k] = (k + 1) * (k + 1); 9 } 10 } 11 for (int l = 1; l < len; l++) { 12 for (int j = l; j < len; j++) { 13 int i = j - l; 14 for (int k = 0; k <= i; k++) { 15 int res = (k + 1) * (k + 1) + dp[i + 1][j][0]; 16 for (int m = i + 1; m <= j; m++) { 17 if (boxes[m] == boxes[i]) { 18 res = max(res, dp[i + 1][m - 1][0] + dp[m][j][k + 1]); 19 } 20 } 21 dp[i][j][k] = res; 22 } 23 } 24 } 25 return dp[0][len - 1][0]; 26 } 27 };