class Solution:
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
if len(nums) == 1:
return nums
# 排序
# 排序之后对nums[i]看前面所有j < i是否nums[i] % nums[j] == 0
nums.sort()
dp = [1] * len(nums) # dp[i]是包含当前nums[i]的最长整除序列长度
pre = [0] * len(nums) # pre[当前i] = 使个数增多1的j
maxSize = maxi = 0
for i in range(len(nums)):
for j in range(i):
if nums[i] % nums[j] == 0 and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
pre[i] = j
if dp[i] > maxSize:
maxSize = dp[i]
maxi = i
res = []
i = maxi
# 回溯
for _ in range(maxSize):
res.append(nums[i])
i = pre[i]
return res[::-1]