Leetcode 368. Largest Divisible Subset

时间:2023-03-08 17:43:20
Leetcode 368. Largest Divisible Subset

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.

If there are multiple solutions, return any subset is fine.

Example 1:

nums: [1,2,3]

Result: [1,2] (of course, [1,3] will also be ok)

Example 2:

nums: [1,2,4,8]

Result: [1,2,4,8]

这种类似求最大值的题一般用DP来解。首先排序,这样就可以只验证后面的数是不是可以整除前面的数。用DP list来保存从一开头到当前这个数字的最长subset的长度,但是由于本题需要返回的是一个list,我们用pre来保存在当前最长subset中上一个元素的位置。

 class Solution(object):
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort()
n = len(nums)
if n == 0:
return []
elif n ==1:
return nums
dp = [1]*n
pre = [None]*n for i in range(n):
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 idx = dp.index(max(dp))
ans = []
while idx is not None:
ans.append(nums[idx])
idx = pre[idx]
return ans