Leetcode 312. Burst Balloons
题意:
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 ofi. 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
思路:
这是很典型的动态规划模型。想了大概半个小时。真是长时间不练,退化太快。转移
状态方程, dp[i][j] 表示i,j之间的数合并后得到的最大值(其中i和j并没有消去。)
状态转移方程: dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i]*nums[k]*nums[j]) 其中要保证,dp迭代右边的数已经算出来。
AC代码:
class Solution {
public:
int maxCoins(vector<int>& nums) {
nums.push_back(1);
nums.push_back(1);
int n = nums.size();
int k = n-1;
while(k>0)
{
nums[k] = nums[k-1];
k--;
}
nums[0] = 1;
vector<int> temp(n, 0);
vector< vector<int>> dp(n, temp);
for (int k=2; k<n; k++)
{
for (int i=0; i<n; i++)
{
int s = i, t = min(n-1, i+k);
for(int j=s+1; j<t; j++)
{
dp[i][t] = max(dp[i][t], dp[i][j]+dp[j][t] + nums[i]*nums[j]*nums[t]);
}
}
}
return dp[0][n-1];
}
};


浙公网安备 33010602011771号