Problem
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
Algorithm
整理一下题意:设想有n个气球,标号0到n-1。每个气球上有一个数字,每个数字标记为nums[i]。要求令所有气球爆炸。若气球i爆炸可以得到nums[left] * nums[i] * nums[right]枚金币,其中left和right都是与i相邻的数。爆炸完成后,left与right变为相邻。要求找到可以收集到的最大金币数。假设nums[-1] = nums[n] = 1,0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100。
典型的动态规划问题,加入分治思想。每次爆炸一个气球,将得到一个乘积。那么对于气球i,将有两种选择:爆炸或者不爆炸。如果不爆炸,那么新的金币数=原金币数;如果爆炸,那么金币数=爆炸得到的金币数+左边的金币数+右边的金币数。于是得到状态转移方程
dp[left][right]=max(dp[left][right], coins[left]*coins[i]*coins[right]+dp[left][i]+dp[i][right]);
需要注意对于头尾两端爆炸的情况。如第0个气球爆炸时,左边已经没有气球了,那么左边的乘数应为1。因此数组大小设为nums.size()+2。最终的求解是在0-(n-1)的区间,故返回dp[0][n-1]。代码如下。
//动态规划+分治,时间复杂度O(n^3)
class Solution {
public:
int maxCoins(vector<int>& nums) {
int coins[nums.size()+2];
int n;
for(n=1;n<nums.size()+1;n++){
coins[n]=nums[n-1];
}
coins[0]=1;
coins[nums.size()+1]=1;
n=nums.size()+2;
int dp[nums.size()+2][nums.size()+2]={};
for(int k=2;k<n;k++){
for(int left=0;left<n-k;left++){
int right=left+k;
for(int i=left+1;i<right;i++){
dp[left][right]=max(dp[left][right],coins[left]*coins[i]*coins[right]+dp[left][i]+dp[i][right]);
}
}
}
return dp[0][n-1];
}
};