Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subse T 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]
Analysis:
Idea: Sort the array and then use Dp[i] to represent the largest collection from 0 to I. In order to get the value of dp[i], we see from i-1 to 0 whether Nums[i]% nums[j] ==0, if yes, dp[i] = max (Dp[i], dp[j]+1), because the array is sorted in descending order, so nums[j] < nums[i], And the number that can be divisible by nums[j] is also bound to be divisible by nums[i.
1 Public classSolution {2 PublicList<integer> Largestdivisiblesubset (int[] nums) {3 if(Nums = =NULL|| Nums.length = =0)return NewArraylist<integer>();4 5 intn =nums.length;6 Arrays.sort (nums);7 int[] DP =New int[n];8Arrays.fill (DP,1);9 int[] Parent =New int[n];TenArrays.fill (Parent,-1);//when a number in the parent array is-1, it means that the number itself is a collection One intMax =1, Max_index =0; A for(inti =1; I < n; i++) {//Calculate Dp[i] - for(intj = i-1; J >=0; j--) {//i > J - if(Nums[i]% nums[j] = =0&& Dp[i] < Dp[j] +1) {//positive distinct numbers in num theDp[i] = Dp[j] +1; -Parent[i] =J; - if(Dp[i] >max) { -Max =Dp[i]; +Max_index =i; - } + } A } at } - returnGenresult (nums, parent, max_index); - } - - PublicList<integer> Genresult (int[] Nums,int[] Parent,intMax_index) { -list<integer> result =NewArraylist<>(); in intITER =Max_index; - while(ITER! =-1) { to Result.add (Nums[iter]); +ITER =Parent[iter]; - } the returnresult; * } $}
Largest divisible subset