问题:
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
解决:
【题意】给定n个气球。每次你可以打破一个,打破第i个,那么你会获得nums[left] * nums[i] * nums[right]个积分。 (nums[-1] = nums[n] = 1)求你可以获得的最大积分数。
① https://segmentfault.com/a/1190000007297715
动态规划。dp[i][j]表示打爆区间[i,j]中的所有气球能得到的最多金币。DP的思想是bottom up
最后的剩下一个气球为i的时候,可以获得的分数为:nums[-1]*nums[i]*nums[n].
那么介于i , j之间的k,有:
dp[i][j] = max(dp[i][j], nums[i - 1] * nums[k] * nums[j + 1] + dp[i][k - 1] + dp[k + 1][j])
( i ≤ k ≤ j ),O(N^2), O(N^2)
class Solution { //15ms
public static int maxCoins(int[] nums) {
int[] tmpnums = new int[nums.length + 2];
System.arraycopy(nums,0,tmpnums,1,nums.length);
tmpnums[0] = 1;
int len = tmpnums.length;
tmpnums[len - 1] = 1;
int[][] dp = new int[len][len];
for (int l = 2;l < len;l ++){
for (int i = 0;i < len - l;i ++){
int j = i + l;
for (int k = i + 1;k < j;k ++){
dp[i][j] = Math.max(dp[i][j],tmpnums[i] * tmpnums[k] * tmpnums[j] + dp[i][k] + dp[k][j]);
}
}
}
return dp[0][len - 1];
}
}
② D&C + Memorization,O(N^3) , O(N^2)
memorization是from top to bottom,每一次都将值分成两部分,然后分别计算。对于在left和right中间的位置i,考虑[left,i]和[i,right]能组成的部分,分别对这两部分进行递归求值。用二维数组记录已经计算过的值,避免重复计算。
class Solution { //10ms
public static int maxCoins(int[] nums) {
int[] tmpnums = new int[nums.length + 2];
for (int i = 1;i <= nums.length;i ++){
tmpnums[i] = nums[i - 1];
}
tmpnums[0] = 1;
tmpnums[tmpnums.length - 1] = 1;
int len = tmpnums.length;
int[][] memo = new int[len][len];
return burst(tmpnums,0,len - 1,memo);
}
public static int burst(int[] nums,int i,int j,int[][] memo){
if (i + 1 == j) return 0;//[i,j]之间没有ballon可以炸掉
if (memo[i][j] > 0){//如果已经计算过了,则直接返回
return memo[i][j];
}
int res = 0;
for (int k = i + 1;k < j;k ++){
res = Math.max(res,nums[i] * nums[k] * nums[j] + burst(nums,i,k,memo) + burst(nums,k,j,memo));//递归获取左右窗口的最大值
}
memo[i][j] = res;
return res;
}
}