https://leetcode.com/problems/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]
Given a sequence of positive integers, find the longest subsequence which satisfies that for every two integers Si and Sj in it, there must be Si%Sj==0 or Sj%Si==0.
We can notice that, if c%b==0, and b%a==0, there must be c%a==0, so we can firstly sort the sequence from smallest to largest element.
And let dp[i] denote the longest subsequence’s length among elements from num[i] to num[end].
Then if j>i and num[j] % num[i]==0, the elements behind j which %num[j]==0, can also %num[i]==0, so dp[i]=dp[j]+1.
But, there maybe several branches which can %num[i]==0,
for example: [1,2,4,8,10,20,40,80],
behind ‘2’, there are two branches, [4,8] and [10,20,40,80],
and we need to find the longest at point ‘2’,
so we should add the judgement, if dp[i]
dp[i] is used to store the longest length, but the target output is a sequence, so for the longest subsequence, we should use a variable ‘max_index’ to record the Start Point, and a list ‘child’ to store the next adjacent index since from Start Point in the subsequence. At the same time, we can also use a variable to record the max length, but it’s not necessary.
for i in range(n-1, -1, -1):
for j in range(i, n):
if nums[j] % nums[i] == 0 and dp[i] < dp[j]+1:
dp[i] = dp[j]+1
class Solution(object):
def largestDivisibleSubset(self, nums):
""" :type nums: List[int] :rtype: List[int] """
n = len(nums)
if n==0 or n==1:
return nums
nums = sorted(nums)
dp = [0]*n
max = 0
max_index = 0
child = [0]*n
result = []
for i in range(n-1, -1, -1):
for j in range(i, n):
if nums[j] % nums[i] == 0 and dp[i] < dp[j]+1:
dp[i] = dp[j]+1
child[i] = j
# To store max subset length and relative start point index
if max < dp[i]:
max = dp[i]
max_index = i
# Construct output subset
i=max_index
for j in range(max):
result.append(nums[i])
i=child[i]
return result
Notice:
If nums==[] or length is 1, return itself.
Don’t forget to sort before dp.
‘=’ and ‘==’