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:
- You may imagine
nums[-1] = nums[n] = 1
. They are not real therefore you can not burst them. - 0 ≤
n
≤ 500, 0 ≤nums[i]
≤ 100
Example:
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
分析
这道题是一道非常难的题目,即使告诉我要是用动态规划的解法去解,我想想不明白怎么利用保存中间的计算,难道用dp[i][j]保存i-j的最大结果吗?但是每次打爆一个气球,两边的就变成相邻的了。[i, j+1]的结果怎么计算呢?
但是看了讨论区的内容,才发现要换一个思路。我们需要用dp[i][j]保存当最后就剩下i和j位置的气球所能得到的最大值。
那么 dp[i][j] = max(dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j]), i < k < j
举例说明,我们将Example给的nums首尾补1为[1,3,1,5,8,1]方便运算:
0 | 1 | 2 | 3 | 4 | 5 | |
0 | 0 | |||||
1 | 0 | |||||
2 | 0 | 0 | 40 | 48 | ||
3 | 0 | 0 | 40 | |||
4 | 0 | 0 | ||||
5 | 0 |
那么就可以得到:
dp[3][5] = max(dp[3][4] + nums[3]*nums[4]*nums[5], dp[4][5] + nums[3]*nums[4]*nums[5]) = 40
dp[2][5] = max(dp[2][i] + dp[i][5] * nums[2]*nums[i]*nums[5]), 2 < i < 5
Code
class Solution {
public:
int maxCoins(vector<int>& nums) {
int len = nums.size();
if (len == 0)
return 0;
nums.insert(nums.begin(), 1);
len += 2;
nums.push_back(1);
vector<vector<int>> dp(len+2, vector<int>(len+2, 0));
for (int i = len-3; i >= 0; i --)
{
for (int j = i + 2; j < len; j ++)
{
int maxNum = 0;
for (int k = i + 1; k < j; k ++)
{
maxNum = max(maxNum, dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j]);
}
dp[i][j] = maxNum;
}
}
return dp[0][len-1];
}
};
运行效率
Runtime: 16 ms, faster than 97.83% of C++ online submissions for Burst Balloons.
Memory Usage: 9.6 MB, less than 10.91% of C++ online submissions for Burst Balloons.