LeetCode 312. Burst Balloons

探讨了如何通过动态规划解决气球爆破问题,旨在获得最大收益。文章提出了一种有效的算法,通过构建DP表格逐步求解最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

"""
首刷:求最大的乘积

思路1:直接搜索 22case
思路2:将nums直接作为str 进行序列化 30case

题解 dp[i][j] 表示从i到j之间的最大收益

错误的思想: k最先爆 #这样写 比如case[3,1,5,8] -> 取1的时候 [3] , [5,8]被拆开了

正确的思想:k是[i,j]中最后爆的那个


"""
class Solution(object):
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums = [1] + nums + [1]  #2段补齐

        dp = [[0 for i in xrange(len(nums))] for j in xrange(len(nums))]
        return self.helper(1,len(nums) - 2,dp,nums)   #[1, len(nums) - 2]这个区间内爆破
        
    def helper(self,i,j,dp,nums):
        if i > j:
            return 0

        if dp[i][j] != 0:
            return dp[i][j]
    
        max_one = 0

        for k in xrange(i,j + 1): #[i,j]之间 所有人都可能是最后1个 包括j
            if j + 1 < len(nums) and i - 1 >= 0:
                #print j + 1
                max_one = max(self.helper(i,k - 1,dp,nums) + nums[i - 1] * nums[k] * nums[j + 1] + self.helper(k + 1,j,dp,nums) , max_one)

        dp[i][j] = max_one
        return max_one
            

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值