Leetcode Difficulty - Poking Balloons (Super Detailed Ideas)

Title:
There are n balloons, numbered from 0 to n - 1, each balloon is marked with a number, and these numbers are stored in the array nums.
You are now asked to pop all the balloons. Pop the i-th balloon, you can get nums[i - 1] * nums[i] * nums[i + 1] coins. Here i - 1 and i + 1 represent the serial numbers of the two balloons adjacent to i. If i - 1 or i + 1 is outside the bounds of the array, treat it as a balloon with number 1.
Find the maximum number of coins that can be obtained.

Solution:
use dp to solve, this dp idea is very wonderful

If there is a group of balloons abcdefghijk, we require the result of this.
For the convenience of calculation, we preprocess it into 1 abcdefghijk 1.
At this time, if we have e left at the end
, is it equivalent to [(1) abcd (e) result] + [ (e) result of fghijk (1)] + [ 1 * e * 1 ]

(What is the premise of this? It is because if it is known that e is the last remaining, then the optimal conditions of these two segments do not interfere with each other, so the value obtained by adding the last remaining balloon to these two parts, It is the optimal solution, so the decision to satisfy the most critical sub- problem cannot affect other unresolved problems later, and has no aftereffect )

Then, for example, let’s look at the paragraph (e) fghijk (1).
Is it the same as the initial situation
? If the last remaining i is
equivalent to [ (e) fgh (i) ] + [ (i) jk (1 ) ] + [ (e) * i * (1) ]

From this it can be concluded that the formula
dp [ i ] [ j ] = dp [ i ] [ k - 1 ] + dp [ k + 1 ] [ j ] + val [ i - 1 ] * val [ j + 1 ] * val [ k ]

Then we can start writing code, attach

class Solution {
public:
    int dp[305][305];
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        nums.insert(nums.begin(), 1);
        nums.push_back(1);
        for(int l = 0; l < n; l++) {
            for(int i = 1; i + l <= n; i++) {
                for(int k = i; k <= i + l; k++) {
                    dp[i][i+l] = max(dp[i][i+l], nums[k] * nums[i-1] * nums[i+l+1] + dp[i][k-1] + dp[k+1][i+l]);
                }
            }
        }
        return dp[1][n];
    }
};

Guess you like

Origin blog.csdn.net/m0_52212261/article/details/128884027