WEEK#12 Dynamic Programming_Burst Ballons

Description of the Problem

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 = 315 + 358 + 138 + 181 = 167


Dynamic Programming

When it comes to questions of maximum or minimum value, use dynamic programming.
Maintain a 2-d array M, in which M[i][j] means the maximum value you can get when bursting a sub array nums[i...j].
For example, M[0][3] means the maximum value we can get by bursting nums[0...3] ([1, 5, 8]). Our goal is to find out M[0...n-1]

The way to find out M[i][j] is
M[i][j] = Max(M[i][k-1] + M[k+1][j] + nums[k]nums[i-1]nums[j+1])
For any i <= k <= j

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        if (nums.size() == 0)
            return 0;
        int length = nums.size();
        vector<vector<int>> Matrix;
        Matrix.resize(length);
        for (int i = 0; i < length; i++)
            Matrix[i].resize(length);

        // first and last of nums are 1. 
        nums.push_back(1);
        nums.insert(nums.begin(), 1);

        int end, max, temp, left, right;
        for (int gap = 0; gap < length; gap++) {
            for (int start = 1; start < length - gap+1; start++) {
                max = 0;
                end = start + gap;
                if (start == end) {
                    Matrix[start-1][end-1] = nums[start - 1] * nums[start] * nums[start + 1];
                } else {
                    for (int LastBurstIndex = start; LastBurstIndex <= end; LastBurstIndex++) {
                        left = LastBurstIndex - 2 >= start - 1 ? Matrix[start - 1][LastBurstIndex - 2] : 0;
                        right = end - 1 >= LastBurstIndex ? Matrix[LastBurstIndex][end - 1] : 0;
                        temp = left + right + nums[start - 1] * nums[LastBurstIndex] * nums[end + 1];
                        if (temp > max)
                            max = temp;
                    }
                    Matrix[start-1][end-1] = max;
                }
            }
        }
        return Matrix[0][length - 1];
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容