首页 > 代码库 > DP-Burst Balloons

DP-Burst Balloons

leetcode312:

https://leetcode.com/problems/burst-balloons/#/description

 

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. Here left and rightare adjacent indices of i. After the burst, the left and right 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://blog.csdn.net/xyqzki/article/details/50255345

 

代码:

class Solution(object):
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) == 0: return 0
        nums = [1] + nums + [1]#这里可以像ref一样,把nums里面的0排除掉
        size = len(nums)
        dp = [[0]*len(nums) for x in range(len(nums))]#这样初始化,[0]*len(nums)是[0,0,0...]

        for k in xrange(2, size):
            for i in xrange(size - k):
                j = i + k
                p = i + 1
                while p < j:
                    dp[i][j] = max(dp[i][j], dp[i][p] + dp[p][j] + nums[i]*nums[p]*nums[j])
                    p += 1
        return dp[0][size - 1]

一开始我自己的想法是把这个问题转化为背包问题

开始时气球队列为空,从0到n依次加入气球

对每个新加入的气球有如下选项:最先爆炸和在先前的某一个气球爆炸后爆炸

但是经过思考发现这样的思路难以实现.要求对于每一个部分记录详细的爆炸轨迹,时间开销十分昂贵

看到xyqzki的攻略后豁然开朗

剩余内容吃完饭后补完

DP-Burst Balloons