[LeetCode] 312. Burst Balloons

题目内容

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]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值