leetcode.312. Burst Balloons
来源:互联网 发布:软件咨询服务合同模板 编辑:程序博客网 时间:2024/05/03 16:14
Given
n
balloons, indexed from 0
to n-1
. Each balloon is painted with a number on it represented by arraynums
. You are asked to burst all the balloons. If the you burst ballooni
you will getnums[left] * nums[i] * nums[right]
coins. Hereleft
and right
are adjacent indices ofi
. After the burst, theleft
andright
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
Example:
Given [3, 1, 5, 8]
Return 167
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
思路
考虑最后一个戳破的气球,这个气球的位置可以把整个气球数组分成两部分。
利用动态规划思路:
动态规划数组:
DP[k][h]:nums[k...h]能戳破气球的最大值
递推关系:
取k<m<h,nums[m]假设是最后一个戳破的气球
则DP[k][h] =
for (m = k+1...h)
max(DP[k][m] + DP[m][h] + nums[k] * nums[m] * nums[h]);
初始值:
需要扩展nums,数组长+2,头和尾分别加入1
DP[k][h]:
当k + 1 = h 或 k = h时,为0;
当k + 2 = h 时,为 nums[k] * nums[k+1] * nums[k+2];
class Solution {public: int maxCoins(vector<int>& nums) { int n = nums.size()+2; vector<int> newnums(n); for (int i = 0;i < n - 2; i++){ newnums[i+1] = nums[i]; } newnums[0] = newnums[n - 1] = 1; vector<int> tmp(n,0); vector<vector<int>> DP(n,tmp); for (int k = 2; k < n; k++){ for (int l = 0; l + k < n; l++){ int h = l + k; for (int m = l + 1; m < h; m++){ DP[l][h] = max(DP[l][h],newnums[l] * newnums[m] * newnums[h] + DP[l][m] + DP[m][h]); } } } return DP[0][n - 1]; }};
0 0
- leetcode 312. Burst Balloons
- [leetcode] 312. Burst Balloons
- LeetCode 312. Burst Balloons
- LeetCode 312. Burst Balloons
- leetcode.312. Burst Balloons
- 【leetcode】312. Burst Balloons
- LeetCode 312. Burst Balloons
- leetcode 312. Burst Balloons
- leetcode 312.Burst Balloons
- Leetcode-312. Burst Balloons
- 【Leetcode】312. Burst Balloons
- 【leetcode】312. Burst Balloons
- 【leetcode】312. Burst Balloons
- LeetCode 312. Burst Balloons
- 【Leetcode】312. Burst Balloons
- 【LeetCode】312. Burst Balloons
- 【LeetCode】312. Burst Balloons
- leetcode 312. Burst Balloons
- mysql字符集相关 Illegal mix of collations (gbk_chinese_***) and (gb2312_chinese_***) for operation '
- SDAU练习三1024
- 慕课网学习笔记之python的布尔运算
- 获取屏幕像素
- python二进制解析strut.upack的错误unpack requires a string argument of length 4
- leetcode.312. Burst Balloons
- UnityShader入门 积雪Shader
- #pragma comment 用法
- openjudge6252 带通配符的字符串匹配
- Codeforces Round #354 (Div. 2) D (BFS)
- Huffman code
- 8253实现定时,使8253输出周期为1秒,高电平:低电平=4:5的脉冲信号
- 数据结构—顺序表的实现
- TCP的长连接与短连接