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];
    }
};
相关推荐
二进制person38 分钟前
Java SE--方法的使用
java·开发语言·算法
OneQ6661 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way1 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
.30-06Springfield2 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
Coding小公仔3 小时前
C++ bitset 模板类
开发语言·c++
凌肖战3 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
菜鸟看点4 小时前
自定义Cereal XML输出容器节点
c++·qt
weixin_478689764 小时前
十大排序算法汇总
java·算法·排序算法
luofeiju4 小时前
使用LU分解求解线性方程组
线性代数·算法
学不动CV了5 小时前
数据结构---线性表理解(一)
数据结构