对于 1799 leetcode 难度是很大的,,我抄写,改写了 别人的
class Solution:
def maxScore(self, nums: List[int]) -> int:
#最多14个数字,摆明了是让状态压缩
n = len(nums)
#---- 预计算一下gcd数组,虽然只有14个数字,但是数字都很大
g = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(i + 1, n):
g[i][j] = self.self_gcd(nums[i],nums[j])
#这里,只需要大的,上三角矩阵
w=1 << n
dp = [0]*w #尽量不用range
for s in range(3, w):
cnt1 = bin(s).count('1')
t,yu = divmod(cnt1, 2)
if not yu:
for i in range(n-1):
for j in range(i+1, n):
x,y=1<<i,1<<j
if s&x and s&y:
if (m:= (dp[s-x-y] + t*g[i][j]))>dp[s]:dp[s]=m
return dp[-1] #最后
def self_gcd(self,a,b):
while b:
t=a%b
a,b=b,t
return a
'''作者:code_learner
链接:https://leetcode.cn/problems/maximize-score-after-n-operations/solution/cpython3-zhuang-ya-dp-by-hanxin_hanxin-azsb/'''
网友评论