爆炸的信号灯在利特CD正计时

2024-05-29 02:18:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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.

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

我有时间做一些测试用例。在

想知道如何改进?请只给我一些提示。在

class Solution(object):
        def recursion(self, nums, index, dp):
            r = -1
            if not nums:
                return 0
            if len(nums) == 1:
                return nums[0]
            if str(nums) in dp:
                return dp[str(nums)]
            if index >= len(nums):
                return 0
            for i in range(len(nums)):
                if i == 0:
                    r = max(r, nums[i]*nums[i+1] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
                elif i == len(nums)-1:
                    r = max(r, nums[i-1]*nums[i] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
                else:
                    r = max(r, nums[i-1]*nums[i]*nums[i+1] + self.recursion(nums[0:i]+nums[i+1:][:], i, dp))
            dp[str(nums)] = r
            return r

        def maxCoins(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            return self.recursion(nums, 0, {})

Tags: theselfrightyoulenreturnifleft

热门问题