分治与动态规划之Burst Balloons问题
来源:互联网 发布:苹果电脑怎么更新软件 编辑:程序博客网 时间:2024/06/10 21:04
Burst Balloons
A.题意
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
题目的大概意思是,给你n个气球,戳破某个气球得到该气球和它左右两个气球上数字的乘积,然后去掉改气球,使得其左右两边的气球变成相邻,问最后所有乘积相加最大值是什么。
题目中给了个例子:
Given [3, 1, 5, 8]
Return 167
它是这样一个过程
[3,1,5,8] –> [3,5,8] –> [3,8] –> [8] –> []
对应的coins则为3*1*5+3*5*8+1*3*8+1*8*1=167
B.思路
我是在leetcode的分治那部分看到这道题的,一开始毫无思路,因为假如要分治,你把(i,j)中的k戳破,然后把该序列分成(i,k-1],[k+1,j)的话两个序列是彼此影响的,因为这时候k-1和k+1变成相邻的了,然后翻看讨论区看到了其实这道题应该换种思路,把k当成是i到j中最后一个戳破的气球,这样子问题之间就没有联系了,就可以分治了,我们结合动态规划用表格来记录i到j的最大结果,就可以得到该迭代式
table[i][j] = max(table[i][j],myNums[i] * myNums[k] * myNums[j] + table[i][k] + table[k][j]);
C.代码实现
class Solution {public: int maxCoins(vector<int>& nums) { int size = nums.size(); int myNums[size + 2]; for (int i = 1;i < size + 1;i++) { myNums[i] = nums[i - 1]; } myNums[0] = 1; myNums[size + 1] = 1; int table[size + 2][size + 2] = {}; for (int i = 0;i < size + 2;i++) { table[i][i] = myNums[i]; } for (int len = 2;len < size + 2;len++) { for (int i = 0;i < size + 2 - len;i++) { int j = i + len; for (int k = i + 1;k < j;k++) { table[i][j] = max(table[i][j],myNums[i] * myNums[k] * myNums[j] + table[i][k] + table[k][j]); } } } return table[0][size + 1]; }};
- 分治与动态规划之Burst Balloons问题
- 动态规划:Burst Balloons
- 312. Burst Balloons 难度:hard 类别:分治、动态规划
- Burst Balloons (第八周 分治 + 动态规划)
- LeetCode----312. Burst Balloons(H) 动态规划
- LeetCode 312. Burst Balloons--动态规划
- 【leetcode题解】【再来,动态规划】【H】【21.8】Burst Balloons
- leetcode之Burst Balloons
- 问题分解,分治与动态规划
- 分治与动态规划
- Burst Balloons
- Burst Balloons
- Burst Balloons
- Burst Balloons
- Burst Balloons
- Burst Balloons
- Burst Balloons
- Burst Balloons
- maven mvn spring-boot:run执行失败
- 软件工程导论3.4题
- H5项目笔记
- js 实现复选框只能选择一项
- PyCharm3.0默认快捷键
- 分治与动态规划之Burst Balloons问题
- spring-boot-admin源码分析及单机监控spring-boot-monitor的实现(三)
- (利用索引)大数据查询
- 获取当前时间戳
- MFC在鼠标自定义的一定的范围内实现拖动窗口移动、错误:不支持尝试执行的操作、实现进度条颜色的渐变或者背景和前景色的改变
- 关于eclipse左边文件栏消失
- Netty4实战第九章:启动Netty应用
- Paragon ntfs for mac 15新增了哪些功能
- 华硕g550jk4700笔记本bios设置u盘启动呢?