Burst Balloons
Given n Balloons, indexed from 0 to n-1 . Each balloon are painted with a number on the IT represented by array nums . You is asked to burst all the balloons. If The burst balloon you'll i get nums[left] * nums[i] * nums[right] coins. Here and is left right adjacent indices of i . After the burst, the and then left right becomes adjacent.
Find The maximum coins you can collect by bursting the balloons wisely.
Note:
(1) May imagine nums[-1] = nums[n] = 1 . They is not real therefore you can not burst them.
(2) 0≤ n ≤ 500, 0≤ nums[i] ≤100
Example:
Given[3, 1, 5, 8]
Return167
Nums = [3,1,5,8]--[3,5,8]--[ 3,8]-- [8]-- [] coins = 3*1*5 + * 5*8 + 1*3*8 + 1*8*1 = 167
https://leetcode.com/problems/burst-balloons/
Divide and conquer + dynamic planning.
Https://leetcode.com/discuss/72216/share-some-analysis-and-explanations
First of all, the idea of violence, n balloons one by one, leaving the n-1 to step in order, until the end, the complexity of the table tle.
Added to the idea of divided treatment, after stepping on a balloon, the array is divided into two parts, but the problem is left and right is not independent, so the result of division is wrong.
Reverse thinking, when stepping on the last balloon, the result is yes, because the left and right sides of the point are the border and the border.
For example, the array [A,b,c,d,e,f,g], which represents any number.
First Remove all 0, add two 1 to the head and tail to indicate the boundary.
The outermost loop is from a to G, which represents the last step of the balloon.
Suppose to traverse to c this point, the last to step on C, then the value of C is fixed, 1 * c * 1.
Then consider both sides, the left side is 1 and c for the boundary, the maximum value, the right is the C and 1 for the boundary to find the maximum value.
The maximum value can be obtained by recursion.
Also open a two-dimensional array to record intermediate results to improve efficiency.
1 /**2 * @param {number[]} nums3 * @return {number}4 */5 varMaxcoins =function(nums) {6 varDP = [], I, Numarr = [1];7 for(i = 0; I <nums.length; i++){8 if(Nums[i]!== 0) Numarr.push (Nums[i]);9 }TenNumarr.push (1); One varLen =numarr.length; A for(i = 0; i < Len; i++){ -Dp[i] = []; - } the returnBurstballoons (1, len-2); - - functionburstballoons (start, end) { - if(Start > End)return0; + if(Dp[start][end])returnDp[start][end]; - varmax =-Infinity; + for(vari = start; I <= end; i++){ Amax = Math.max (max, numarr[start-1] * numarr[i] * numarr[end + 1] + atBurstballoons (Start, i-1) + burstballoons (i + 1, end)); - } -Dp[start][end] =Max; - returnMax; - } -};
[Leetcode] [Java] Burst Balloons