312. Burst Balloons
Hard
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:
You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
Example:
Input: [3,1,5,8]
Output: 167
Explanation: nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 315 + 358 + 138 + 181 = 167
题意
给定含有n个带有权重的气球的序列nums,戳破一个气球可以得到该气球的权重与左右两个的气球的权重的乘积,然后左右两个气球变成相邻气球。求按最优顺序戳破所有气球可以得到的最大权重。
思路
动态规划。dp[i][j]表示在n个气球序列中只戳破[i:j]的子列的所有气球所得到的最大权重,递推式为
dp[i][j] = max(nums[i-1] * nums[k] * nums[j+1] + dp[i][k-1] + dp[k+1][j])
时间复杂度为O(n3),空间复杂度为O(n2).
代码
class Solution {
public int maxCoins(int[] nums) {
int n = nums.length, i = 0, j = 0, k = 0, tmp = 0, curMax = 0, leftMul = 1, rightMul = 1;
if (n == 0) {
return 0;
}
if (n == 1) {
return nums[0];
}
int[][] dp = new int[n][n];
for (k=0; k<n; ++k) {
dp[k][k] = k == 0? nums[k] * nums[k+1]: (k == n-1? nums[k-1] * nums[k]: nums[k-1] * nums[k] * nums[k+1]);
}
for (j=1; j<n; ++j) {
for (i=0; i<n-j; ++i) {
curMax = 0;
for (k=i; k<=i+j; ++k) {
tmp = 0;
if (k-1 >= i) {
tmp += dp[i][k-1];
}
if (k+1<=i+j) {
tmp += dp[k+1][i+j];
}
leftMul = i == 0? 1: nums[i-1];
rightMul = i+j == n-1? 1: nums[i+j+1];
tmp += leftMul * nums[k] * rightMul;
curMax = Math.max(tmp, curMax);
}
dp[i][i+j] = curMax;
}
}
return dp[0][n-1];
}
}