class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
count = [0]*(n)
pre = [-1]*(n)
maxlen,index = float('-inf'),-1
nums.sort()#要排序
for i in range(n):
for j in range(i-1,-1,-1):
if nums[i]%nums[j]==0 and count[j]+1>count[i]:#只要能%最后元素j就行,不必所有元素都%.
count[i] = count[j]+1
pre[i] = j
if count[i] > maxlen:
maxlen = count[i]
index = i
res = []
while index!=-1:
res.append(nums[index])
index = pre[index]
return res
用set慢慢扩展
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
count = [0]*(n)
pre = [-1]*(n)
maxlen,index = float('-inf'),-1
nums.sort()#要排序
s = {-1:set()}
for x in nums:
s[x] = max((s[d] for d in s if x%d == 0),key = len)|{x}
return list(max(s.values(),key = len))