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
举个例子,数组[3,1,5],计算最大的积分。
解题过程如下:
数组开头和末尾加元素1,变为[1,3,1,5,1]
区域长度为1时
[1,1] 最后打破气球1,resulyt[1,1]=3
[2,2] 最后打破气球2,result[2,2]=15
[3,3] 最后打破气球3,result[3,3]=5
区域长度为2时:
[1,2] 最后打破气球1,temp1=0+result[2,2]+1*3*5=30;最后打破气球2,temp2=result[1][1]+0+1*1*5=8;所以result[1,2]=30
[2,3] 最后打破气球2,temp1=0+result[3,3]+3*1*1=8;最后打破气球3,temp2=result[2][2]+0+3*5*1=30;所以result[2,3]=30
区域长度为3时:
[1,3] 最后打破气球1,temp1=0+result[2,3]+3*1*1=33;最后打破气球2,temp2=result[1,1]+result[3,3]+1*1*1=9;最后打破气球3,temp3=result[1,2]+0+5*1*1=35;所以result[1,4]=35
例题最终答案为35
class Solution {
public:
int maxCoins(vector<int>& nums) {
int n = nums.size();
//数组两边 nums[0]=1,nums[n]=1
nums.insert(nums.begin(), 1);
nums.insert(nums.end(), 1);
int result[505][505]={};
for(int length=1;length<=n;length++)
{
//length长度[letf,right]里找最大的
for(int left=1;left<=(n-length+1);left++)
{
int right=left+length-1;
for(int x=left;x<=right;x++)
{
int temp=result[left][x-1]+result[x+1][right]+nums[x]*nums[left-1]*nums[right+1];
/*cout<<left<<" "<<right<<" "<< temp<<endl;*/
if(temp>result[left][right])
{
result[left][right]=temp;
}
}
}
}
return result[1][n];
}
};