LeetCode----312. Burst Balloons(H) 动态规划

1 题目

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


2 分析

用dp[i][j]存储从ij最大的coin数

在数组的前后添加1

确定左边界、右边界,枚举出长度为len(从3开始)的所有可能coin数

以最后一个被戳破的气球为界,将数组分为左右两边

状态方程如代码所示


3 C++ 实现

class Solution {
public:
    int maxCoins(vector<int>& nums) {

		nums.insert(nums.begin(), 1);
		nums.push_back(1);
        
        int n = nums.size();
        int dp[n][n] = {};
        for (int len = 3; len <= n; len++)
            for (int l = 0; l <= n - len; l++) {
                int r = l + len - 1;
                for (int i = l + 1; i < r; i++)
                    dp[l][r] = max(dp[l][r], 
                        nums[l] * nums[i] * nums[r] + dp[l][i] + dp[i][r]);
            }
    
        return dp[0][n - 1];
        
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值