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];
    }
};
相关推荐
2301_815279527 分钟前
实战分享实现 C++ 管理类单例模式:特点与最佳实践
javascript·c++·单例模式
洛水水11 分钟前
【力扣100题】22. 矩阵置零
算法·leetcode·矩阵
Liangwei Lin12 分钟前
LeetCode 78. 子集
数据结构·算法·leetcode
多加点辣也没关系25 分钟前
数据结构与算法|第二十四章:算法思维总结与实战
算法·代理模式
旺仔老馒头.26 分钟前
【C++】类和对象(二)
开发语言·c++·后端·类和对象
炽烈小老头30 分钟前
【每天学习一点算法 2026/05/11】排序链表
学习·算法·链表
wefg135 分钟前
一些零散的算法
c++·算法
khalil102038 分钟前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水
Hcoco_me38 分钟前
Ai:Agent/ infra / 智驾 / 推广算法 题库
人工智能·深度学习·算法·自动驾驶·剪枝
项目申报小狂人38 分钟前
提出了一种带双向搜索的粒子群优化算法,一种基于双四元数运动优化的新型无人机3D路径规划方法及应用
算法·3d·无人机