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
DP problem, began not to come out alas, looked at others. is from the left and right between the spacing starting from 2, has been pushed to the difference n-1 this situation. The code looks like this:
1 classSolution {2 Public:3 Static BOOLNocoins (inta)4 {5 returnA = =0;6 }7 intMaxcoins (vector<int>&nums) {8Nums.erase (Remove_if (Nums.begin (), Nums.end (), Nocoins), Nums.end ());//Notice how this is handled. Call remove before calling erase9 if(nums.size () = =0) Ten return 0; OneNums.resize (nums.size () +2); ACopy (Nums.begin (), Nums.end ()-2, Nums.begin () +1); -nums[0] = Nums[nums.size ()-1] =1; - intSZ =nums.size (); the intDP[SZ][SZ] = {}; - for(intInterval =2; Interval < SZ; ++interval) {//interval refers to the interval between left and right. - for(intleft =0; Left < Sz-interval; ++Left ) { - intright = left +interval; + for(intj = left +1; J < Right; ++J) {//to exhaust every possible value between Left-right -Dp[left][right] = max (Dp[left][right], dp[left][j] + nums[left]*nums[j]*nums[right] +dp[j][right]); +}//Note that the reason for the left and right here is that the number is covered by Dp[left][j . A } at } - returndp[0][sz-1];//This is the end result. - } -};
Leetcode Oj:burst Balloons (break balloon)