[Dynamic Programming] LeetCode-312. Poke the balloon

312. Poke the balloon

Title description

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.

Now you are required to pop all the balloons. Poke 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 exceeds the boundary of the array, then it is treated as a balloon with the number 1.

Find the maximum number of coins that can be obtained.

Example 1:
Input: nums = [3,1,5,8]
Output: 167
Explanation:
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3 1 5 + 3 5 8 + 1 3 8 + 1 8 1 = 167
Example 2:

Input: nums = [1,5]
Output: 10

Problem-solving ideas

class Solution_312 {
    
    
    public int maxCoins(int[] nums) {
    
    
        int n = nums.length;
        //添加两侧的虚拟气球
        int[] points = new int[n + 2];
        //nums[-1] = nums[n] = 1,直接把这两个边界加进去,形成一个新的数组
        points[0] = points[n +1] = 1;
        for (int i = 1; i <= n; i++) {
    
    
            points[i] = nums[i - 1];
        }
        //base case
        int[][] dp = new int[n + 2][n + 2];
        //开始状态转移
        //i应该从下到上
        for (int i = n; i >= 0; i--) {
    
    
            //j应该从左到右
            for (int j = i + 1; j < n + 2; j++) {
    
    
                //最后戳破的气球是哪个
                for(int k = i + 1; k < j; k++){
    
    
                    //择优做选择
                    dp[i][j] = Math.max(
                            dp[i][j],
                            dp[i][k] + dp[k][j] + points[i] * points[j] * points[k]
                    );
                }
            }
        }
        return dp[0][n + 1];
    }
}

Guess you like

Origin blog.csdn.net/qq_35655602/article/details/115256235