LeetCode-Largest Divisble Subset

LiBlog發表於2016-07-24

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]

Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.

Analysis:

Sort the array, then for nums[i], if nums[i] % nums[j] == 0, then nums[i] is in the largest divisible set of nums[j]. We just need to find out the largest subset of nums[i].

Solution:

 1 public class Solution {
 2     public List<Integer> largestDivisibleSubset(int[] nums) {
 3         List<Integer> resList = new LinkedList<Integer>();        
 4         if (nums.length == 0) return resList;
 5 
 6         Arrays.sort(nums);
 7         int[] size = new int[nums.length];
 8         int[] pre = new int[nums.length];
 9 
10         int maxSize = 0;
11         int maxInd = -1;
12 
13         for (int i=0;i<nums.length;i++){
14             int localMax = 0;
15             int localInd = -1;
16             for (int j=0;j<i;j++)
17                 if (nums[i] % nums[j] == 0 && localMax < size[j]+1){
18                     localMax = size[j]+1;
19                     localInd = j;
20                 }
21             if (localInd == -1){
22                 localMax = 1;
23                 localInd = -1;
24             } 
25             size[i] = localMax;
26             pre[i] = localInd;
27             
28 
29             if (maxSize < localMax){
30                 maxSize = localMax;
31                 maxInd = i;
32             }
33         }
34         
35         resList.add(nums[maxInd]);
36         int preInd = pre[maxInd];
37         while (preInd != -1){
38             maxInd = preInd;
39             preInd = pre[maxInd];
40             resList.add(nums[maxInd]);
41         }
42         Collections.reverse(resList);
43         
44         return resList;
45     }
46 }