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.
- 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
Given [4, 1, 5, 10]
Return 270
nums = [4, 1, 5, 10] burst 1, get coins 4 1 5 = 20
nums = [4, 5, 10] burst 5, get coins 4 5 10 = 200
nums = [4, 10] burst 4, get coins 1 4 10 = 40
nums = [10] burst 10, get coins 1 10 1 = 10
Total coins 20 + 200 + 40 + 10 = 270
Solutions:
- 区间类DP
- 考虑nums[-1] = nums[n] = 1,所以扩展数组为n+2, 其中头尾设置为1
- State: dp[i][j] 表示区间i, j所能取得的最大值(dp[n+2][n+2])
- Function: dp[i][j] = max(dp[i][k-1]+A[i-1]*A[k]*A[j+1]+dp[k+1][j])
- Initial: dp[i][i] = A[i-1]*A[i]*A[i+1]
- Answer: dp[1][n]
public int maxCoins(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}
int n = nums.length;
int[] array = new int[n+2];
array[0] = array[n+1] = 1;
for (int i = 0; i < n; ++i) {
array[i+1] = nums[i];
}
int[][] dp = new int[n+2][n+2];
boolean[][] flag = new boolean[n+2][n+2];
return search(1, n, dp, flag, array);
}
private int search(int l, int r, int[][] dp, boolean[][] flag, int[] nums) {
if (flag[l][r]) {
return dp[l][r];
}
flag[l][r] = true;
for (int k = l; k <= r; ++k) {
int value = nums[l-1] * nums[k] * nums[r+1];
int left = search(l, k-1, dp, flag, nums);
int right = search(k+1, r, dp, flag, nums);
dp[l][r] = Math.max(dp[l][r], value+left+right);
}
return dp[l][r];
}