# LeetCode – Largest Divisible Subset (Java)

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]

Java Solution 1 - DFS

 public class Solution { List answer; public List largestDivisibleSubset(int[] nums) { if(nums==null || nums.length==0) return new ArrayList();   Arrays.sort(nums);   int[] max = new int[1]; List result = new ArrayList(); helper(nums, 0, result, max); return answer; }   public void helper(int[] nums, int start, List result, int[] max){ if(result.size()>max[0]){ max[0]=result.size(); answer=new ArrayList(result); }   if(start==nums.length) return;   for(int i=start; i

Java Solution 2 - DP

 public List largestDivisibleSubset(int[] nums) { List result = new ArrayList(); if(nums==null||nums.length==0) return result;   Arrays.sort(nums);   int[] t = new int[nums.length]; int[] index = new int[nums.length]; Arrays.fill(t, 1); Arrays.fill(index, -1);   int max=0; int maxIndex=-1;   for(int i=0; i=0; j--){ if(nums[i]%nums[j]==0 && t[j]+1>t[i]){ t[i]=t[j]+1; index[i]=j; } }   if(max=0){ result.add(nums[i]); i=index[i]; }   return result; }
Category >> Algorithms >> Interview
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Vanessa Chang

Hey, I think this isn’t correct, as you allow any number that is a factor of i to be added to the list, which will not necessarily be divisible with each other. For example: {1, 2, 4, 5, 20}. 2 & 5, and 4 & 5 are not divisible, yet they will both be on the result list.

• Hooman

Let’s make it more readable:

private List largestDivisibleSubset(int[] nums) {
// first sort the array
Arrays.sort(nums);

List result = new ArrayList();
List tmp;

for (int i = 0; i < nums.length; i++) {
tmp = new ArrayList();