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 numsi - 1 * numsi * numsi + 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 <= numsi <= 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];
    }
};
相关推荐
ALex_zry3 分钟前
C++26 std::inplace_vector 详解:零堆分配的定容向量
开发语言·c++
卷无止境23 分钟前
C++ 类型转换变迁之路:从隐式转换到 static_cast
c++·后端
LJHclasstore_luo28 分钟前
【题解】WebGoC 102683.大雨过后
算法·goc编程
MrZhao40029 分钟前
Agent 如何持续工作:任务持久化、后台执行与定时唤醒
算法
用户7017207390031 分钟前
密码学之分组密码
算法
MrZhao40041 分钟前
Agent 长上下文处理机制:Context Compact 与 Memory 的协同
算法
h_a_o777oah1 小时前
【动态规划】区间 DP :三层循环逻辑与模板实现细节(洛谷 P1880)
c++·算法·动态规划·acm·区间dp·化环为链·石子合并
从此以后自律1 小时前
迪杰斯特拉
算法
QiLinkOS1 小时前
第三视觉理解徐玉生与他的商业活动(32)
大数据·c++·人工智能·算法·开源协议
KaMeidebaby1 小时前
卡梅德生物技术快报|实操手册:CXCL4 蛋白原核表达全套工艺,两步层析去除蛋白多聚体附完整电泳数据
人工智能·算法·机器学习·架构·spark