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:

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

Example 2:

1
2
Input: [1,2,4,8]
Output: [1,2,4,8]

思路

DP.
状态转移方程: dp[x] = max(dp[x], dp[y] + 1) 其中: 0 <= y < x 且 nums[x] % nums[y] == 0
再通过一个辅助数组pre回溯。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:
return []
res = []
nums = sorted(nums)
dp = [1] * len(nums)
pre = [None] * len(nums)
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
index = dp.index(max(dp))
while index is not None:
res.append(nums[index])
index = pre[index]
return res[::-1]