Leetcode312. Burst Balloons

You are given n balloons, indexed from 0 to n - 1. Each balloon is painted with a number on it represented by an array nums. You are asked to burst all the balloons.

If you burst the ith balloon, you will get nums[i - 1] * nums[i] * nums[i + 1] coins. If i - 1 or i + 1 goes out of bounds of the array, then treat it as if there is a balloon with a 1 painted on it.

Return the maximum coins you can collect by bursting the balloons wisely.

Example 1:

Input: nums = [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的经典题目

因为对区间长度有要求,至少是3,所以遍历时选择先对区间长度遍历,再对区间起点遍历。注意:在对区间起点进行遍历的时候,遍历的终点需要依据区间长度而定。

dp[i][j]为开区间i,j中能得到的最大分数。将dp[i][j]拆解为dp[i][k], dp[k][j]即可得到状态转移方程。

所以还需要一个for循环 for(i+1, j)来对dp[i][j]的所有可能拆解方案进行遍历。

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        size = len(nums)
        arr = [0] * (size+2)
        arr[0] = arr[size+1] = 1
        arr[1:size+1] = nums
        
        dp = [[0 for _ in range(size + 2)] for _ in range(size + 2)]
        
        for l in range(3, size+3):
            for i in range(size+3-l):
                j = i + l - 1
                for k in range(i + 1, j):
                    dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + arr[i]*arr[j]*arr[k])
        
        return dp[0][size+1]

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值