312. Burst Balloons

Classical interval DP question.

From observation, we know the left interval and right interval are independent to each other, only and only if the common balloons of two interval didnt brust.

Here are some illustration:

[1, 3, 4, 2, 1]

left interval : [1, 3, 4]

right interval: [4, 2, 1]

unless the 4 havent brusted, the left interval scores and right interval scores are independent.

Once we have this information, rest of the operations is easy think of.

We just need to enumerate the length of big interval, and cut it off to be left interval and right interval. Our dp array would updates the optimal scores of different length of interval one by one. Thus, when we cut the interval into two parts, we are able to get the scores of these two parts imediately and we just need to calculate the scores we get from the balloons we brust where we cut the interval into two parts.

About correctness of this algorithm:

As long as we dont brust the balloon at the edge of the interval, it will not have double counting problem. you can try to illustrate the process.

You would ask how can we calculate the scores of num[0] and num[n]?

We can try to add 1 at the head of the num and the tail of the num.

Code:

class Solution {
public:
    int maxCoins(vector<int>& num) {
        int n = num.size();
        vector<int>nums;
        nums.push_back(1);
        for(int i = 0; i < n; i++){
            nums.push_back(num[i]);
        }
        nums.push_back(1);
        n = nums.size();
        int dp[302][302];
        memset(dp, 0, sizeof(dp));
        for(int len = 3; len <= n; len++){
            for(int left = 0; left <= n - len; left++){
                int right = left + len - 1;
                for(int mid = left + 1; mid < right; mid++){
                    dp[left][right] = max(dp[left][right], dp[left][mid] + dp[mid][right] + nums[left]*nums[mid]*nums[right]);
                }
            }
        }

        return dp[0][n - 1];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值