[leetcode]312. Burst Balloons
来源:互联网 发布:淘宝客小猪优惠券 编辑:程序博客网 时间:2024/05/29 18:22
divide and conquer
题目:
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
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
思路:
在区间[i, j]中,最后的元素的乘积与其两边的值无关,因此可以作为一个边界,其左右两边的结果只与自身的值有关,不与对方的值有关。
所以设left
dp[left][right] = max(dp[left][right], dp[left][m]+dp[m][right]+newnums[left]*newnums[m]*newnums[right]);
代码:
class Solution {public: int maxCoins(vector<int>& nums) { vector<int> newnums(nums.size()+2); int size = nums.size()+2; newnums[0] = newnums[size-1] = 1; int i; for (i = 1; i < size-1; i++) { newnums[i] = nums[i-1]; } int dp[size][size] = {}; for (int k = 2; k < size; k++) { for (int left = 0; left < size-k; left++) { int right = left+k; for (int m = left+1; m < right; m++) { dp[left][right] = max(dp[left][right], dp[left][m]+dp[m][right]+newnums[left]*newnums[m]*newnums[right]); //std::cout << dp[left][right] << endl;; } } } return dp[0][size-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
- Atcoder arc 084 D
- centOs7 忘记root密码
- 如何删除strut2校验后<s:fielderror>在jsp页面输出时的小黑点和自动换行?
- 自我总结的HTML
- TankWar游戏(图片版)----阶段四
- [leetcode]312. Burst Balloons
- [Oracle 11g r2(11.2.0.4.0)]Oracle Golden Gate Training-workshop5
- Python高级编程-如何实现反向迭代?
- jquery html标签替换
- matplotlib函数库使用bar绘制柱状图
- 无名科创开源飞控公告
- 最大公约数和最小公倍数
- mysql最新版explain详解来自官网直译(4)
- Python高级编程-如何在在一个for循环中迭代多个可迭代对象