LeetCode 312. Burst Balloons(动态规划)

312. Burst Balloons

Hard

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:

Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 315 + 358 + 138 + 181 = 167

题意

给定含有n个带有权重的气球的序列nums,戳破一个气球可以得到该气球的权重与左右两个的气球的权重的乘积,然后左右两个气球变成相邻气球。求按最优顺序戳破所有气球可以得到的最大权重。

思路

动态规划。dp[i][j]表示在n个气球序列中只戳破[i:j]的子列的所有气球所得到的最大权重,递推式为
dp[i][j] = max(nums[i-1] * nums[k] * nums[j+1] + dp[i][k-1] + dp[k+1][j])
时间复杂度为O(n3),空间复杂度为O(n2).

代码

class Solution {
    public int maxCoins(int[] nums) {
        int n = nums.length, i = 0, j = 0, k = 0, tmp = 0, curMax = 0, leftMul = 1, rightMul = 1;
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return nums[0];
        }
        int[][] dp = new int[n][n];
        for (k=0; k<n; ++k) {
            dp[k][k] = k == 0? nums[k] * nums[k+1]: (k == n-1? nums[k-1] * nums[k]: nums[k-1] * nums[k] * nums[k+1]);
        }
        for (j=1; j<n; ++j) {
            for (i=0; i<n-j; ++i) {
                curMax = 0;
                for (k=i; k<=i+j; ++k) {
                    tmp = 0;
                    if (k-1 >= i) {
                        tmp += dp[i][k-1];
                    }
                    if (k+1<=i+j) {
                        tmp += dp[k+1][i+j];
                    }
                    leftMul = i == 0? 1: nums[i-1];
                    rightMul = i+j == n-1? 1: nums[i+j+1];
                    tmp += leftMul * nums[k] * rightMul;
                    curMax = Math.max(tmp, curMax);
                }
                dp[i][i+j] = curMax;
            }
        }
        return dp[0][n-1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值