[LeetCode] Burst Balloons
来源:互联网 发布:电脑软件连不上网络 编辑:程序博客网 时间:2024/05/02 01:16
public class Solution { // 从最后一个burst的入手,dp[i][j]为i与j之间所有均已经burst的话所得分数的max public int maxCoins(int[] iNums) { int[] nums = new int[iNums.length + 2]; int n = 1; // 将其中为0的剪枝 for(int x : iNums){ if (x > 0) nums[n++] = x; } // 先赋值,后自增,如果是nums[++n]的话就是先自增,后赋值 nums[0] = nums[n++] = 1; int[][] dp = new int[n][n]; // k是left与right之间的距离 for (int k = 2; k < n;k++){ for (int left = 0; left < n - k; left++) { int right = left + k; for (int i = left + 1; i < right; i++) { dp[left][right] = Math.max(dp[left][right], nums[left] * nums[i] * nums[right] + dp[left][i] + dp[i][right]); } } } return dp[0][n-1]; }}
本题是一道非常明显的DP问题,之所以没有思路,原因在于没有找到合适的DP矩阵来表示状态,由此得出一个教训,实现DP问题的时候一定要从bottom to top和top to bottom两种角度去考虑问题。本题即为reverse think,反向思考。
另:本题有两种解法,另一种解法如下:
public class Solution { public int maxCoins(int[] iNums) { int[] nums = new int[iNums.length + 2]; int n = 1; for(int x : iNums){ if (x > 0) nums[n++] = x; } nums[0] = nums[n++] = 1; int[][] dp = new int[n][n]; return burst(dp, nums, 0, n - 1); } private int burst(int[][] dp, int[] nums, int left, int right) { if (left == right - 1) return 0; if (dp[left][right] > 0) return dp[left][right]; int ans = 0; for (int i = left + 1; i < right; i++) { ans = Math.max(ans, nums[left] * nums[i] * nums[right] + burst(dp, nums, left, i) + burst(dp, nums, i, right)); } dp[left][right] = ans; return ans; }}
0 0
- leetcode Burst Balloons
- Burst Balloons | LeetCode
- leetcode之Burst Balloons
- leetcode 312 Burst Balloons
- [LeetCode]Burst Balloons
- leetcode 312 : Burst Balloons
- 【LEETCODE】312-Burst Balloons
- LeetCode Burst Balloons
- leetcode 312. Burst Balloons
- [leetcode] Burst Balloons
- [leetcode] 312. Burst Balloons
- leetcode:Burst Balloons
- [LeetCode] Burst Balloons
- LeetCode 312. Burst Balloons
- LeetCode 312. Burst Balloons
- leetcode笔记--Burst Balloons
- leetcode.312. Burst Balloons
- LeetCode:Burst Balloons
- android的 deeplink与服务路由的思考
- 模拟退火算法(SA,Simulated Annealing)思想
- mongodb基础系列——java操作mongodb实现图片文件功能
- 现货代理,贵金属代理怎么选择一个好的平台?
- Learn Unity(0)——basic C# for Unity
- [LeetCode] Burst Balloons
- 剑指offer-面试题26:复杂链表的复制
- Eclipse下Maven工程多模块继承和聚合的创建
- 大数据工程师:大数据的java基础 第四周
- 如何提高程序的健壮性,增加判断。
- android studio 开发 Execution failed for task
- cubic-bezier贝塞尔曲线CSS3动画工具
- 简单对象访问协议
- ViewController的生命周期