368. Largest Divisible Subset
Total 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 subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8] Result: [1,2,4,8]
思路:
定义T[n]为最大值为nums[n]的满足题意的子集元素个数。
显然如果存在i(i<n),有nums[n]%nums[i],T[n]=max{T[i]+1};否则,T[n]=1。
代码:
1 class Solution { 2 public: 3 vector<int> largestDivisibleSubset(vector<int>& nums) { 4 int i,j,len=nums.size(),m=0,mi; 5 vector<int> T(len,0); 6 vector<int> son(len,0); 7 sort(nums.begin(),nums.end()); 8 for(i=0;i<len;i++){ 9 for(j=i;j>=0;j--){ 10 if(nums[i]%nums[j]==0&&T[j]+1>T[i]){ 11 T[i]=T[j]+1; 12 son[i]=j; 13 } 14 } 15 if(T[i]>m){ 16 m=T[i]; 17 mi=i; 18 } 19 } 20 vector<int> re; 21 for(i=0;i<m;i++){ 22 re.insert(re.begin(),nums[mi]); 23 mi=son[mi]; 24 } 25 return re; 26 } 27 };