[LeetCode] Remove Boxes

来源:互联网 发布:惠州乐知英语 编辑:程序博客网 时间:2024/06/05 20:15

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)

好难的一道题,第二遍做还是要在看一便其他人的解法

public class Solution {public int removeBoxes(int[] boxes) {dp=new int[boxes.length][boxes.length][boxes.length];return dfs(0,boxes.length-1,0,boxes);}int[][][] dp;public int dfs(int i,int j,int k,int[] boxes){if(i>j) return 0;if(dp[i][j][k]!=0) return dp[i][j][k];while(i<=j-1&&boxes[j]==boxes[j-1]){k++;j--;}int re=dfs(i,j-1,0,boxes)+(k+1)*(k+1);//对第j个单独处理的情况for(int t=i;t<j;t++){//对第j个合并的情况if(boxes[t]==boxes[j]){re=Math.max(re, dfs(i,t,k+1,boxes)+dfs(t+1,j-1,0,boxes));}}dp[i][j][k]=re;return re;}}

.

原创粉丝点击