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
nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> []
coins = 315 + 358 + 138 + 181 = 167
Ideas: DP, 逆向思维,等价关系,state i为最后一个burst ballon i。
Because only the first and last balloons we are sure of their adjacent balloons before hand!
For the first we have nums[i-1]nums[i]nums[i+1] for the last we have nums[-1]nums[i]nums[n].
result = Math.max(result,
subMax(memo, nums, left, i) + nums[left] * nums[i] * nums[right] + subMax(memo, nums, i, right));
扩展数组+2,去零
Code:
public int maxCoins(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] extendNums = new int[nums.length+2];
int n = 1;
for (int m : nums) {
if (m > 0) {
extendNums[n++] = m;
}
}
extendNums[0] = extendNums[n++] = 1;
int[][] memo = new int[n][n];
return subMax(memo, extendNums, 0, n - 1);
}
private int subMax(int[][] memo, int[] nums, int left, int right) {
if (left+1 == right) {
return 0;
}
if (memo[left][right] > 0) {
return memo[left][right];
}
int result = 0;
for (int i = left+1; i < right; ++i) {
result = Math.max(result,
subMax(memo, nums, left, i) + nums[left] * nums[i] * nums[right] + subMax(memo, nums, i, right));
}
memo[left][right] = result;
return result;
}