Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in T His subset Satisfies:si% SJ = 0 or Sj% Si = 0.
If There is multiple solutions, return to any subset is fine.
Example 1:
Nums: [1,2,3]result: [Up] (of course, [1,3] would also be OK)
Example 2:
Nums: [1,2,4,8]result: [1,2,4,8]
This type of problem, which is similar to maximum value, is usually solved by DP. Sort first, so that you can only verify that the following number is not divisible by the preceding number. A DP list is used to save the length of the longest subset from the beginning to the current number, but since the subject needs to return a list, we use the pre to hold the position of the previous element in the longest subset.
1 classsolution (object):2 defLargestdivisiblesubset (Self, nums):3 """4 : Type Nums:list[int]5 : Rtype:list[int]6 """7 Nums.sort ()8n =Len (nums)9 ifn = =0:Ten return [] One elifN ==1: A returnNums -DP = [1]*N -Pre = [none]*N the - forIinchrange (n): - forJinchRange (i): - ifnums[i]% Nums[j] = = 0 andDP[J] +1 >Dp[i]: +DP [i] = Dp[j] + 1 -Pre[i] =J + AIDX =Dp.index (Max (DP)) atAns = [] - whileIdx is notNone: - ans.append (Nums[idx]) -IDX =Pre[idx] - returnAns
Leetcode 368. Largest divisible subset