博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 312. Burst Balloons_hard tag: 区间Dynamic Programming
阅读量:4313 次
发布时间:2019-06-06

本文共 1992 字,大约阅读时间需要 6 分钟。

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

 

这个题目的思路也是利用 区间Dynamic Programming, 思想跟类似, 

动态表达式为: 

dp[i][j] 是得到的 [i,j] 里面气球的最大值

for k in [i,j]:

  value_m = ballons[i-1] * ballons[k] * ballons[j+1]

  dp[i][j] = max(dp[i][j], dp[i][k-1] + value_m + dp[k+1][j])

init:

dp[i][i] = ballons[i-1]* ballons[i]* ballons[i+1]

dp[i][j]  = 0 if j < i

 

1. Constraints

1) size [0, 500]

2) element [0, 100]

 

2. Ideas

 

Dynamic Programming      T: O(n^2)    S; O(n^2)

3. Code

class Solution:    def burstBallons(self, nums):        n = len(nums)        ballons = [1] + nums + [1] # plus the corner case        dp = [[0]*(n+2) for _ in range(n+2)] # for corner case        flag = [[0]*(n+2) for _ in range(n+2)]        def helper(l, r):            if flag[l][r]:                return dp[l][r]            if l == r:                dp[l][r] = ballons[l-1] * ballons[l] * ballons[l+1]            elif l < r:                for k in range(l, r+1): # k belongs [l, r], so it is r + 1                    value_m = ballons[l-1] * ballons[k] * ballons[r+1]                    value_l = helper(l, k-1)                    value_r = helper(k+1, r)                    dp[l][r] = max(dp[l][r], value_l + value_m + value_r)            flag[l][r] = 1            return dp[l][r]        return helper(1, n)

 

转载于:https://www.cnblogs.com/Johnsonxiong/p/9399184.html

你可能感兴趣的文章
页面中调用系统常用的对话框需要用到的classid
查看>>
cygwin下的目录软连接
查看>>
eclipse控制台不显示输出的解决办法
查看>>
Java中的TCP/UDP网络通信编程
查看>>
cordova学习:事件Events
查看>>
lincode167 - Add Two Numbers - easy
查看>>
大叔手记(3):Windows Silverlight/Phone7/Mango开发学习系列教程
查看>>
在Delphi中使用C++对象(转)
查看>>
mac 特殊符号的操作
查看>>
C++原创应用类库和工具类库
查看>>
FLOW CONTROL
查看>>
Maze迷宫问题(求最优解)
查看>>
mvc2 使用jquery.ajax发送数据以及显示数据
查看>>
【长期维护】C++休闲(修仙)躲方块小游戏
查看>>
Qt入门(15)——使用窗口部件
查看>>
Qt入门(16)——组装窗口部件
查看>>
raid卡MegaCli工具使用说明
查看>>
Trie树
查看>>
Mysql支持的数据类型(总结)
查看>>
对测试转开发的一些想法
查看>>