312. 戳气球

class Solution:
    def maxCoins(self, nums: List[int]) -> int:
        # DP 因为dp[left][right] = argmax(dp[left][i]+dp[i][right]+left*i*right) 
        # 这个遍历顺序就是,先中间,后两边 所以将left,right都指向最右,然后开始遍历
        l = len(nums)
        vals = [1]+nums+[1]
        # 注意初始化的意义是 在没有操作以前最大值为0
        dp = [[0]*(l+2) for _ in range(l+2)]
        # left right都是不取得,所以为了使得left,right中间有值, right至少=left+2
        # 1 3158 1 left 从5开始 right从1开始 k=[8]
        for left in range(l-1,-1,-1):
            for right in range(left+2,l+2):
                for k in range(left+1,right):
                    dp[left][right] = max(dp[left][right], dp[left][k]+dp[k][right]+vals[left]*vals[right]*vals[k])
        return dp[0][-1]










        # 记忆化搜索,固定left 和 right, 遍历搜索 left*i*right+search(left,i)+search(i,right) 最大时的i值
        # 然后再固定 left,i; i,right 
        # 超时
        # @lru_cache(None)
        # def search_all(left,right):
        #     if left >= right-1: # left = 3 right = 4
        #         return 0
        #     res = 0
        #     for num in range(left+1,right):
        #         total = vals[left]*vals[num]*vals[right] + search_all(left,num)+search_all(num,right)
        #         res = max(res,total)                
        #     # print(res,maxNum)
        #     return res
        # vals = [1]+nums+[1]
        # return search_all(0,len(nums)+1)
        

  https://leetcode-cn.com/problems/burst-balloons/

 

posted @ 2020-12-21 15:13  ChevisZhang  阅读(122)  评论(0编辑  收藏  举报