题目内容
https://leetcode-cn.com/problems/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.
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
题目思路
这道题目在微软的在线考试题目中出现过,可以考虑使用一个二维的动态规划数组进行解题。例如题中给出了一串数字3,1,5,8,我们需要考虑的是对于这一组数字而言,以哪个数字作为最后一个切割对象时,整体序列是最大的。这种情况下,它的计算方式就是左侧的部分最大+右侧的部分最大+选择数字*边界元素1*边界元素2。所以以3为最小集合,dp(i,j)表示以i,j为边界元素的序列的最大值。所以对于一个以k为切分点的序列(i,j,k)来说,它的最大值就是dp(i,j)+dp(j,k)+nk*ni*nj。通过这个过程我们可以用动态规划来算出。
程序代码
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums=[1]+nums+[1]
l=len(nums)
dp=[[0]*l for _ in range(l)]
for size in range(2,l):
#print(size)
for i in range(0,l-size):
j=i+size
#print(i,j)
for k in range(i+1,j):
#print(i,k,j)
dp[i][j]=max(dp[i][j],nums[i]*nums[k]*nums[j]+dp[i][k]+dp[k][j])
return dp[0][l-1]