Question:
N balloons are given. Each time you can break one and break the I, you will get Nums [left] * Nums [I] * Nums [right] credits. (Nums [-1] = Nums [N] = 1) calculate the maximum number of points you can obtain. 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 = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167dp [I] [J ~ Between J.
We can imagine that when the last balloon is I, the score is Nums [-1] * Nums [I] * Nums [N].
Then, the X between I and j Includes DP [I] [J] = max (DP [I] [J], DP [I] [x-1] + Nums [I-1] * Nums [x] * Nums [J + 1] + dp [x + 1] [J]); this is very similar to the question of matrix multiplication.
1 public int maxCoins(int[] nums) { 2 int len = nums.length; 3 int[]num = new int[len+2]; 4 int[][]dp = new int[len+2][len+2]; 5 for(int i = 0;i<=len+1;i++) 6 if(i==0||i==len+1)num[i] = 1; 7 else num[i] = nums[i-1]; 8 int j = 0,temp = 0; 9 for(int k = 1;k<=len;k++) {10 for(int i = 1;i<=len-k+1;i++) {11 j = i+k-1;12 for(int x = i;x<=j;x++) {13 temp = dp[i][x-1]+num[i-1]*num[x]*num[j+1]+dp[x+1][j];14 dp[i][j] = dp[i][j]>temp?dp[i][j]:temp;15 }16 }17 }18 return dp[1][len];19 }
Dynamic Planning-burst ballons