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
题目描述:有n个气球,编号0…n-1,每个气球用一个数字表示,存在数组nums中,现在你被要求打破所有的气球。如果你打破气球i可以获得nums[left] * nums[i] * nums[right] 个硬币,left与right分别是i的左右邻居,当i被打破之后,left与right变邻接了。找到你打破气球所能得到硬币的最大值。
思路:假设dp[i][j]表示打破[i,j]范围内气球所能获得硬币的最大值,那么存在如下的递推关系:
dp[i][j] = max(dp[i][j], nums[i]*nums[k]*nums[j] + dp[i][k-1] + dp[k+1][j]) k的范围为[i,j]
可以这么理解,选择[i,j]之间的一个气球打破,那么将[i,j]分成了[i,k-1],[k+1,j]这两段以及打破气球所获的硬币nums[i]*nums[k]*nums[j],而另外两段内的硬币数便可以用同样的方法求解。
代码如下:
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
//在nums的头和尾添加哨兵
nums.insert(nums.begin(), 1);
nums.push_back(1);
vector<vector<int>> dp(n+2, vector<int>(n+2,0));
for(int step = 0; step <= n; ++step){//step
for(int i = 1; i <= n - step; ++i){
int j = i + step;
for(int k = i; k <= i+step; ++k){
dp[i][j] = max(dp[i][j], nums[i - 1] * nums[k] * nums[j + 1] + dp[i][k - 1] + dp[k + 1][j]);
}
}
}
return dp[1][n];
}
};