0
点赞
收藏
分享

微信扫一扫

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 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

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[k][h]:nums[k...h]能戳破气球的最大值
递推关系:
取k<m<h,nums[m]假设是最后一个戳破的气球
则DP[k][h] =
for (m = k+1...h)
max(DP[k][m] + DP[m][h] + nums[k] * nums[m] * nums[h]);
初始值:
需要扩展nums,数组长+2,头和尾分别加入1
DP[k][h]:
当k + 1 = h 或 k = h时,为0;
当k + 2 = h 时,为 nums[k] * nums[k+1] * nums[k+2];

class Solution {
public int maxCoins(int[] nums) {
//DP: the result depends on the last burst balloon, which seprate the array into 2 subarray.
//DP: by adding 1 to head and tail, DP[i,i] = 0 and DP[i,i+2] = num[i] * num[i+1] * num[i+2]
int n = nums.length+2;
int[] newnums = new int[n];
for (int i = 0;i < n - 2; i++){
newnums[i+1] = nums[i];
}
newnums[0] = newnums[n - 1] = 1;
int[][] DP = new int[n][n];
for (int k = 2; k < n; k++){
for (int l = 0; l + k < n; l++){
int h = l + k;
for (int m = l + 1; m < h; m++){
DP[l][h] = Math.max(DP[l][h],newnums[l] * newnums[m] * newnums[h] + DP[l][m] + DP[m][h]);
}
}
}
return DP[0][n - 1];
}
}


举报

相关推荐

0 条评论