class Solution:
def maxCoins(self, nums) -> int:
self.res = 0
def bt(nums, score):
n = len(nums)
if n ==0:
self.res = max(self.res ,score)
return
for i in range(n):
tmp = nums
s=0
if n==1:
s = nums[0]
elif i == 0:
s = nums[i] *nums[i+1]
elif i == n-1:
s = nums[i-1]*nums[i]
else:
s = nums[i-1]*nums[i]*nums[i+1]
nums = nums[0:i] + nums[i + 1:]
bt(nums, score+s)
nums = tmp
bt(nums, 0)
return self.res
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + s[i] * s[k] * s[j])
戳(i,k) 戳(k,j) 戳k
class Solution:
def maxCoins(self, nums) -> int:
n = len(nums)
s = nums.copy() # 辅助数组
s = [1] + s + [1]
dp = [[0] * (n + 2) for _ in range(n + 2)]
for i in range(n - 1, -1, -1):
for j in range(i + 1, n + 2):
for k in range(i + 1, j):
dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + s[i] * s[k] * s[j])
return dp[0][n + 1]