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];
    }
};
相关推荐
写后端的胖头鱼20 小时前
一文详解B+树原理(附场景+示例)
数据结构·b树
怕浪猫21 小时前
RAG 面试 6 连问,从原理到优化全部覆盖
python·算法·面试
无线通信科研笔记1 天前
IEEE TVT 2026 论文精读与完整复现|相位误差如何重塑近场 RIS 的幅相响应
论文阅读·人工智能·python·算法·论文笔记
mmmmath_31 天前
二叉树の递归遍历
算法
All for pursuit.1 天前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
小师兄吃牛肉1 天前
C语言中的nullptr有必要吗
c语言·c++·算法
WL学习笔记1 天前
日期类(C++)
开发语言·c++·日期类实现
H.莓飛1 天前
【C++】命名空间、缺省参数、函数重载与引用
linux·开发语言·c++·visual studio
一只小小的芙厨1 天前
【线性DP】
学习·算法·动态规划
xxwl5851 天前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构