Leetcode 312. Burst Balloons[hard]
来源:互联网 发布:直播音效软件下载 编辑:程序博客网 时间:2024/06/06 20:58
题目:
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
虽然leetcode标记是hard,但其实就是一个最简单的区间dp。
dp[i][j]表示戳爆i-j所能得到的最高分,则状态转移方程为:
dp[lt][rt] = max(dp[lt][rt], dp[lt][ i - 1] + dp[i + 1][rt] + v[i] * v[lt - 1] * v[rt + 1])
采用记忆化搜索实现。
class Solution {public: vector<int> v; int dp[510][510]; bool vis[510][510]; int maxCoins(vector<int>& nums) { v.clear(); v.push_back(1); for (int i = 0; i < nums.size(); i++) { v.push_back(nums[i]); } v.push_back(1); memset(vis, 0, sizeof vis); dp[1][nums.size()] = calc(1, nums.size()); return dp[1][nums.size()]; } int calc(int lt, int rt) { if (lt > rt) return 0; if (vis[lt][rt]) return dp[lt][rt]; if (lt == rt) { vis[lt][lt] = true; return dp[lt][lt] = v[lt - 1] * v[lt] * v[lt + 1]; } dp[lt][rt] = calc(lt + 1, rt) + v[lt - 1] * v[lt] * v[rt + 1]; for (int i = lt + 1; i <= rt; i++) { dp[lt][rt] = max(dp[lt][rt], calc(lt, i - 1) + calc(i + 1, rt) + v[i] * v[lt - 1] * v[rt + 1]); } vis[lt][rt] = true; return dp[lt][rt]; }};
- LeetCode 312. Burst Balloons 【hard】
- Leetcode 312. Burst Balloons[hard]
- LeetCode 312. Burst Balloons[hard]
- LeetCode[312. Burst Balloons] 难度[hard]
- LeetCode 312. Burst Balloons(Hard)
- [hard]312. Burst Balloons
- 312. Burst Balloons[hard]
- 312. Burst Balloons Hard
- LeetCode #312 - Burst Balloons - Hard
- 312. Burst Balloons (Hard)
- 题解——Leetcode 312. Burst Balloons 难度:Hard
- 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
- 字符串计数-求复合条件字典序个数
- 后台验证码
- 小米考试(电话号码)
- c
- UE4 Texture Streaming Pool 运行时红色显示关闭
- Leetcode 312. Burst Balloons[hard]
- FFmpeg视频转码技巧之二次编码
- 小甲鱼python视频教程053~055论一只爬虫的自我修养
- ds1302通信
- 原始的分享-菌-003--软件系列的说
- Truth News
- Android Handler机制剖析
- codeforces 708E——前缀和优化dp
- 到底什么是微信小程序?