题目描述
Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.
Find the maximum coins you can collect by bursting the balloons wisely.
样例
Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
算法1
$O(n^3)$
类似 Acwing 320. 能量项链 区间DP
C++ 代码
class Solution {
public:
int maxCoins(vector<int>& w) {
w.insert(w.begin(), 1);
w.push_back(1);
int n = w.size();
int f[n+1][n+1];
memset(f, 0, sizeof f);
for(int len = 3; len <= n; len++){
for(int l = 0; l + len - 1 < n; l++){
int r = l + len - 1;
for(int k = l + 1; k < r; k++)
f[l][r] = max(f[l][r], f[l][k]+f[k][r] +w[l]*w[k]*w[r]);
}
}
return f[0][n-1];
}
};