Leetcode 368. Largest divisible subset

Source: Internet
Author: User

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]


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.


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

Contact Us

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.