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
My code:
class Solution(object):
def maxCoins(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
if len(nums)==1:
return nums[0]
num1=[1]+nums+[1]
nums=num1
m=len(nums)
self.N=m
self.record=[[-1]*m for i in range(m)]
result=self.calcu_max(nums,0,len(nums)-1)
#print(self.record)
return result
def calcu_max(self,nums,i,j):
if i>=j:
return 0
if self.record[i][j]!=-1:
return self.record[i][j]
#for j in range(i,len(nums)):
for k in range(i+1,j):
self.record[i][j]=max(self.record[i][j],nums[i]*nums[j]*nums[k]+self.calcu_max(nums,i,k)+self.calcu_max(nums,k,j))
if self.record[i][j]==-1:
self.record[i][j]=0
return self.record[i][j]
def maxCoins1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)+2
A = [1]+nums+[1]
f = [[0]*(n) for _ in range(n)]
for i in range(n,-1,-1):
for j in range(i,n):
for k in range(i+1,j):
f[i][j] = max(f[i][j], f[i][k] + f[k][j] + A[i]*A[k]*A[j])
print(f)
return f[0][n-1]