【LEETCODE】312-Burst Balloons

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 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值