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]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution(object):
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if not nums:return []
nums.sort()
n = len(nums)
dp = [1]*n
for i in range(1,n):
for j in range(i-1,-1,-1):
if nums[i]%nums[j] == 0:
dp[i] = max(dp[i],dp[j] + 1)
#根据dp数组找出符合规定的一条数据
out = []
curval = 0
curlen = 0
for i in range(len(dp)):
if curlen < dp[i]:
curlen = dp[i]
curval = nums[i]
out.append(curval)
for i in range(n-1,-1,-1):
if curval%nums[i] == 0 and dp[i] == curlen - 1:
curlen = curlen-1
curval = nums[i]
out.append(curval)
return out