今天的征程还是星辰大海
题目
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.
Note:
(1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
(2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:
Given [3, 1, 5, 8]
Return 167
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
思路
这道题的dp虽然难了一点需要用区间来表示状态,但其实状态转移方程还是比较好理解的。
状态:用区间dp[left][right]表示在区间[left,right]中不包括left和right的气球爆炸后能得到的最多硬币。为了便于计算在num数组左右各插入一个coins为1的气球。
状态转移:对区间内不包括左右端点的气球遍历:
dp[l][r] = max(dp[l][r], nums[l]*nums[i]*nums[r]+dp[l][i]+dp[i][r]);
也即遍历每个气球取左右端点为相邻两个气球时爆炸能得到的硬币数和当前最大硬币数相比较,若更大则替换当前最大状态。
最后的结果用dp[0][nums.size()+1]表示包括全部气球的区间爆炸得到最大硬币数。
代码
class Solution {
public:
int maxCoins(vector<int>& nums) {
vector<int> newnums(nums.size()+2);
vector<vector<int> > dp(nums.size()+2);
for(int i = 0; i < nums.size() + 2; i++) {
if(i == 0 || i == nums.size() + 1) newnums[i] = 1;
else newnums[i] = nums[i-1];
dp[i].resize(nums.size()+2);
for(int j = 0; j < nums.size() + 2; j++) dp[i][j] = 0;
}
for(int k = 2; k < nums.size()+2; k++) {
for(int l = 0; l < nums.size()+2-k; l++) {
int r = l + k;
for(int i = l + 1; i < r; i++) {
dp[l][r] = max(dp[l][r], newnums[l]*newnums[i]*newnums[r]+dp[l][i]+dp[i][r]);
}
}
}
return dp[0][nums.size()+1];
}
};