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