leetcode-Remove Boxes
来源:互联网 发布:淘宝护肤品禁用词 编辑:程序博客网 时间:2024/05/24 00:46
/*
* 采用记忆搜索
* dp[left][right][k]:boxes编号从left到right,且左边有k个boxe跟boxes[left]相同
* 思路:左边的k个可以先跟boxes[left]移除,也可以保留下来跟右边的bxoes[left]相同的移除
* dp[left][right][k]=Max{(k+1)^2+dp[left+1][right][0],max(dp[left+1][m-1][0]+dp[m][right][k+1])};
* m为left+1~right与boxes[left]相同的编号
*/
public static int removeBoxes(int[] boxes) {
int[][][] dp=new int[boxes.length][boxes.length][boxes.length];
return dpf(boxes,0,boxes.length-1,0,dp);
}
public static int dpf(int[] boxes,int left,int right,int k,int[][][] dp){
if(left>right)return 0;
if(dp[left][right][k]>0)return dp[left][right][k];
int res=(k+1)*(k+1)+dpf(boxes,left+1,right,0,dp);
for(int m=left+1;m<=right;m++)
if(boxes[left]==boxes[m])
res=Math.max(res,dpf(boxes,left+1,m-1,0,dp)+dpf(boxes,m,right,k+1,dp));
dp[left][right][k]=res;
return res;
}
* 采用记忆搜索
* dp[left][right][k]:boxes编号从left到right,且左边有k个boxe跟boxes[left]相同
* 思路:左边的k个可以先跟boxes[left]移除,也可以保留下来跟右边的bxoes[left]相同的移除
* dp[left][right][k]=Max{(k+1)^2+dp[left+1][right][0],max(dp[left+1][m-1][0]+dp[m][right][k+1])};
* m为left+1~right与boxes[left]相同的编号
*/
public static int removeBoxes(int[] boxes) {
int[][][] dp=new int[boxes.length][boxes.length][boxes.length];
return dpf(boxes,0,boxes.length-1,0,dp);
}
public static int dpf(int[] boxes,int left,int right,int k,int[][][] dp){
if(left>right)return 0;
if(dp[left][right][k]>0)return dp[left][right][k];
int res=(k+1)*(k+1)+dpf(boxes,left+1,right,0,dp);
for(int m=left+1;m<=right;m++)
if(boxes[left]==boxes[m])
res=Math.max(res,dpf(boxes,left+1,m-1,0,dp)+dpf(boxes,m,right,k+1,dp));
dp[left][right][k]=res;
return res;
}
阅读全文
0 0
- LeetCode Week8: Remove boxes
- [LeetCode] Remove Boxes
- leetcode-Remove Boxes
- leetcode 546. Remove Boxes
- [leetcode]546. Remove Boxes
- [Leetcode] 546. Remove Boxes 解题报告
- Remove Boxes
- leetcode 546. Remove Boxes 很复杂的DP
- 546. Remove Boxes
- 546. Remove Boxes (HARD)
- Leetcode546. Remove Boxes
- Leedcode 19 Remove Boxes
- 546. Remove Boxes
- 546. Remove Boxes
- Leetcode546. Remove Boxes(Hard)
- Boxes
- Add or remove buttons from message dialog boxes
- LeetCode:Remove Element
- OPNET14.5 + win7 + VS2008安装详解(内附所需安装包)
- C++标准库笔记:13.12.3 以辅助函数完成I/O
- linux编译出现undefined reference to symbol 'pthread_create错误解决方案
- 每天一个Linux命令(46):vmstat命令
- Git常用命令
- leetcode-Remove Boxes
- ViewPager滑动事件讲解
- linux系统svn操作
- Git使用本地仓库之基本操作
- 每天一个Linux命令(47):iostat命令
- 生产者/消费者问题
- POJ 1297 Supermarket 笔记
- C 币获得方法
- Find Bottom Left Tree Value