Given n balloons, indexed from0 ton-1. Each balloon is painted with a number on it represented by arraynums. You are asked to burst all the balloons. If the you burst ballooni you will getnums[left] * nums[i] * nums[right] coins. Hereleft andright are adjacent indices ofi. After the burst, theleft andright 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 = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167
参考:
http://www.hrwhisper.me/leetcode-burst-balloons/
我们可以想象:最后的剩下一个气球为i的时候,可以获得的分数为:nums[-1]*nums[i]*nums[n].
那么介于i,j之间的x,有:
dp[i][j]=max(dp[i][j],DP(i,x-1)+nums[i-1]*nums[x]*nums[j+1]+DP(x+1,j));
小白+自学=都快怀疑自己的智商了 不开森
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n=len(nums)
nums=[1]+nums+[1]
dp=[[0 for j in range(n+2)] for i in range(n+2)] #
def DP(i,j):
if dp[i][j]>0:
return dp[i][j]
for x in range(i,j+1): #在 i,j 这个当前状态中,x为最后剩下的那个数
dp[i][j]=max(dp[i][j],DP(i,x-1)+nums[i-1]*nums[x]*nums[j+1]+DP(x+1,j)) #矩阵存着最大值of 把x爆破后的分+x被剩下前的状态
return dp[i][j]
return DP(1,n) #最终要求的就是状态就是 1,n