368. Largest Divisible Subset
阿新 • • 發佈:2018-12-11
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]