312. Burst Balloons

312. Burst Balloons
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

已知我们有n个气球,每个气球有一个数,爆一个气球可以获得这个气球的数*相邻两个气球的数(越界默认为1)个金币,求爆破这n个气球所能获得的最大金币额数。

首先枚举法是不现实的,这将会是巨量的计算量。但是我们可以使用动态规划来计算。

首先记每个气球的数字存放在nums中,一共有len个气球,dp[i][j]是从nums[i]到nums[j]的子串的最大金币额数。显而易见,一定有一个气球是最后爆破的,假设它对应nums[k],那么可知总金额为爆破最后一个气球获得的金币数,与爆破这个气球的左边的所有气球的最大金币数,和爆破这个气球的右边的所有气球的最大金币数之和。也就是

dp[0][len1]=1nums[k]1+dp[0][k1]+dp[k+1][len1] d p [ 0 ] [ l e n − 1 ] = 1 ∗ n u m s [ k ] ∗ 1 + d p [ 0 ] [ k − 1 ] + d p [ k + 1 ] [ l e n − 1 ]

而为了确定这个最后爆破的气球,只要将所有情况都遍历一次,选出最终总金币数最大的那个即可。而要求1*nums[k]*1+dp[0][k-1]+dp[k+1][len-1],我们首先得求出dp[0][k-1]和dp[k+1][len-1],那么原理同求dp[0][len-1],但是要注意的是,由于dp[0][len-1]的左右两端越界默认为1,而其他子串的情况并不一定会产生越界,我们设子串的最左端为left,最右端为right,那么

dp[left][right]=max(dp[left][right],nums[left1]nums[k]nums[right+1]+dp[left][k1]+dp[k+1][right]) d p [ l e f t ] [ r i g h t ] = m a x ( d p [ l e f t ] [ r i g h t ] , n u m s [ l e f t − 1 ] ∗ n u m s [ k ] ∗ n u m s [ r i g h t + 1 ] + d p [ l e f t ] [ k − 1 ] + d p [ k + 1 ] [ r i g h t ] )

对子串中的每个数都计算一次,求出最大值赋给dp[left][right]。一层一层求出来,最后便能求出dp[0][len-1],也就是我们想要的结果。

为方便处理越界情况,我们在nums的前面插入1,后面添加1。dp矩阵在在外围添加了一圈,并赋初值为0。
参考代码如下:

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int len = nums.size();
        // init
        nums.insert(nums.begin(), 1);
        nums.push_back(1);
        int dp[len+2][len+2];
        for(int i = 0; i < nums.size(); i++)
            for(int j = 0; j < nums.size(); j++)
                dp[i][j] = 0;
        // calculate
        for(int l = 1; l <= len; l++) {
            for(int left = 1; left <= len - l + 1; left++) {
                int right = left + l -1;
                for(int i = left; i <= right; i++) {
                    int temp = nums[left-1]*nums[i]*nums[right+1] + dp[left][i-1] + dp[i+1][right];
                    dp[left][right] = max(dp[left][right], temp);
                }
            }
        }
        return dp[1][len];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值