一、题目描述
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
二、主要思路
动态规划解题,首先在vector的首尾各插入一个1,二维数组dp用于记录从下标为i到j的最大值,对应的状态转移方程为
dp[l][r]=max(dp[l][r],(dp[l][i]+dp[i][r]+nums[l]*nums[i]*nums[r])),即在l、r和len取不同值的时候,dp[l][r]取
dp[l][i]+dp[i][r]+nums[l]*nums[i]*nums[r]的最大值,表示nums[l]、nums[i]和nums[r]是最后相乘的三个数,他们彼此之间数取最大值,即dp[l][i]和dp[i][r]。
最后返回从坐标0到n-1的dp值。
三、代码实现
class Solution {
public:
int maxCoins(vector<int>& nums) {
nums.insert(nums.begin(),1);
nums.push_back(1);
int n=nums.size();
vector<vector<int>>dp(n,vector<int>(n));
for(int len=3;len<=n;len++){
for(int l=0;l<=n-len;l++){
int r=l+len-1;
for(int i=l+1;i<r;i++){
dp[l][r]=max(dp[l][r],(dp[l][i]+dp[i][r]+nums[l]*nums[i]*nums[r]));
}
}
}
return dp[0][n-1];
}
};