前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >LeetCode 0312 - Burst Balloons

LeetCode 0312 - Burst Balloons

作者头像
Reck Zhang
发布2021-08-11 11:14:32
发布2021-08-11 11:14:32
24100
代码可运行
举报
文章被收录于专栏:Reck ZhangReck Zhang
运行总次数:0
代码可运行

Burst Balloons

Desicription

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:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

代码语言:javascript
代码运行次数:0
运行
复制
Input: [3,1,5,8]
Output: 167 
Explanation: 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

Solution

代码语言:javascript
代码运行次数:0
运行
复制
class Solution {
public:
    int maxCoins(std::vector<int>& nums) {
        auto balloons = std::vector<int>(nums.size() + 2);
        balloons[0] = balloons[balloons.size() - 1] = 1;
        for(int i = 1; i < balloons.size() - 1; i++) {
            balloons[i] = nums[i - 1];
        }
        
        auto dp = std::vector<std::vector<int>>(balloons.size(), std::vector<int>(balloons.size(), 0));
        for(int length = 2; length < balloons.size(); length++) {
            for(int left = 0; left + length < balloons.size(); left++) {
                int right = left + length;
                for(int i = left + 1; i < right; i++) {
                    dp[left][right] = std::max(dp[left][right], balloons[left] * balloons[i] * balloons[right] + dp[left][i] + dp[i][right]);
                }
            }
        }
        
        return dp[0][balloons.size() -1];
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Burst Balloons
    • Desicription
    • Solution
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档