# Leetcode 368. Largest divisible subset

Source: Internet
Author: User

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.

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

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.