LeetCode312. Burst Balloons——区间dp

文章目录

一、题目

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

Example 1:

Input: nums = [3,1,5,8]

Output: 167

Explanation:

nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []

coins = 31 5 + 35 8 + 13 8 + 18 1 = 167

Example 2:

Input: nums = [1,5]

Output: 10

Constraints:

n == nums.length

1 <= n <= 300

0 <= nums[i] <= 100

二、题解

cpp 复制代码
class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size();
        vector<int> arr(n+2,1);
        for(int i = 1;i <= n;i++){
            arr[i] = nums[i-1];
        }
        vector<vector<int>> dp(n+2,vector<int>(n+2));
        for(int i = 1;i <= n;i++){
            dp[i][i] = arr[i-1] * arr[i] * arr[i+1];
        }
        for (int l = n, ans; l >= 1; l--) {
			for (int r = l + 1; r <= n; r++) {
				ans = max(arr[l - 1] * arr[l] * arr[r + 1] + dp[l + 1][r],
						arr[l - 1] * arr[r] * arr[r + 1] + dp[l][r - 1]);
				for (int k = l + 1; k < r; k++) {
					ans = max(ans, arr[l - 1] * arr[k] * arr[r + 1] + dp[l][k - 1] + dp[k + 1][r]);
				}
				dp[l][r] = ans;
			}
		}
        return dp[1][n];
    }
};
相关推荐
Dream it possible!5 分钟前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
float_com20 分钟前
【背包dp-----分组背包】------(标准的分组背包【可以不装满的 最大价值】)
算法·动态规划
丶Darling.1 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
L_cl2 小时前
【Python 算法零基础 3.递推】
算法
醍醐三叶2 小时前
C++文件操作--2 二进制文件操作
开发语言·c++
int型码农2 小时前
数据结构第七章(四)-B树和B+树
数据结构·b树·算法·b+树
li星野2 小时前
C++:C++内存管理
开发语言·c++
溟洵2 小时前
【C++ Qt】布局管理器
开发语言·c++·qt
我家大宝最可爱2 小时前
c++动态链接库
开发语言·c++
乌萨奇也要立志学C++2 小时前
【C++详解】string各种接口如何使用保姆级攻略
c++