Weekly LeetCode Algorithm Questions (16) 312. Burst Balloons

Weekly LeetCode Algorithm Questions (16)

Title: 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.

solution analysis

This problem requires O(n^3) complexity. Intuitively, the three-layer cycle, the length of the first-layer window, from small to large; the left and right endpoints of the first-layer window; the relationship between each position in the first-layer window and the length of the previous window is dp[left][right] = max( dp[left][right], dp[left][i] + dp[i][right] + num[left] * num[i] * num[right]), where the two dimensions of dp represent the Left and right endpoint subscripts.

The explanation is that a balloon in the cyclic selection window of the third layer is punctured, and the second and first layers cyclically select the position and size of the window. Because the window changes from small to large, the situation in the large window has been determined by the small window.

C++ code

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int len = nums.size();
        int * num = new int[len + 2];
        for (int i = 1; i < len + 1; i++) {
            num[i] = nums[i - 1];
        }
        num[0] = 1;
        num[len + 1] = 1;

        int **dp = new int*[len + 2];
        for (int i = 0; i < len + 2; i++) {
            dp[i] = new int[len + 2];
            memset(dp[i], 0, sizeof(int) * (len + 2));
        }
        for (int width = 3; width <= len + 2; width++) {
            for (int left = 0; left + width - 1 <= len + 1; left++) {
                int right = left + width - 1;
                for (int i = left + 1; i < right; i++) {
                    dp[left][right] = max(dp[left][right], dp[left][i] + dp[i][right] + num[left] * num[i] * num[right]);
                }
            }
        }
        return dp[0][len + 1];
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325712950&siteId=291194637