【leetcode每日刷题】【dp】312. Burst Balloons

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 right are 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:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Input: [3,1,5,8]
Output: 167 
Explanation: 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

使用动态规划的方法:关键是确定状态转移方程

其dp数组dp[i, j]代表区间[i, j]的最大爆破money,所以其区间的确定顺序应该是根据长度从小到大,先确定dp[i][i], 再确定dp[i][i+2].....直到填满整个右上方的区域,以此图为例,其区间确定顺序应该是([3], 3) -> ([1], 15) -> ([5], 40) -> ([8], 40) -> ([3, 1], 30) -> ([1, 5], 135) -> ([5, 8], 48) -> ([3, 1, 5], 159) -> ([1, 5, 8], 159) -> ([3, 1, 5, 8], 167)

所以遍历应该是按长度从1到4:然后确定start和end,然后确定start, end窗口中的最大值,这是就需要依赖状态转移方程,已经知道了小区间内的最大爆破值,在遍历的时候爆破第k个气球的时候最大值为左边的爆破值和右边的爆破值相加和当前爆破值的和,即 dp[start][end] = max(dp[start][end], nums[start-1] * nums[k] * nums[end+1] + dp[start][k-1] + dp[k+1][end])

0    0    0    0    0    0
0    3    30   159  167  0
0    0    15   135  159  0
0    0    0    40   48   0
0    0    0    0    40   0
0    0    0    0    0    0
class Solution(object):
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = [1] + nums + [1]
        size = len(nums)
        dp =[[0 for col in range(size)] for row in range(size)]
        for length in range(1, size-1):
            for start in range(1, size-length):
                end = start + length - 1
                for k in range(start, end+1):
                    dp[start][end] = max(dp[start][end], nums[start-1] * nums[k] * nums[end+1] + dp[start][k-1] + dp[k+1][end])
        return dp[1][size-2]

        
if __name__ == "__main__":
    nums = [3, 1, 5, 8]
    solution = Solution()
    print(solution.maxCoins(nums))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值