368. Largest divisible subsetTotal accepted:864 Total submissions:2728 difficulty:medium
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: [1,2] (of course, [1,3 ] would also be OK)
Example 2:
Nums: [1,2,4,8]result: [1,2,4 ,8]
Ideas:
Defines the number of subset elements that satisfy test instructions t[n] for a maximum value of nums[n].
Obviously if I (i<n) exists, there is nums[n]%nums[i],t[n]=max{t[i]+1}; otherwise, t[n]=1.
Code:
1 classSolution {2 Public:3vector<int> Largestdivisiblesubset (vector<int>&nums) {4 intI,j,len=nums.size (), m=0, MI;5vector<int> T (len,0);6vector<int> Son (len,0);7 sort (Nums.begin (), Nums.end ());8 for(i=0; i<len;i++){9 for(j=i;j>=0; j--){Ten if(nums[i]%nums[j]==0&&t[j]+1>T[i]) { Onet[i]=t[j]+1; Ason[i]=J; - } - } the if(t[i]>L) { -m=T[i]; -Mi=i; - } + } -vector<int>re; + for(i=0; i<m;i++){ A Re.insert (Re.begin (), Nums[mi]); atMi=Son[mi]; - } - returnre; - } -};
Leetcode 368. Largest divisible subset