# Question

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]

# Code

``````public class Solution {
public class Data {
public int index;
public int count;
public int pre;

public Data(int index, int count, int pre) {
this.index = index;
this.count = count;
this.pre = pre;
}
}

public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> result = new ArrayList<>();
if (nums == null || nums.length == 0) return result;
if (nums.length == 1) {
return result;
}

Arrays.sort(nums);

Data[] dp = new Data[nums.length];
dp[0] = new Data(0, 1, 0);
int max = 1;
Data record = dp[0];

for (int i = 1; i < dp.length; i++) {
dp[i] = new Data(i, 1, i);
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0) {
if (dp[j].count + 1 > dp[i].count) {
dp[i].count = dp[j].count + 1;
dp[i].pre = j;
}
if (dp[i].count > max) {
max = dp[i].count;
record = dp[i];
}
}
}
}

while (record.index != record.pre) {
record = dp[record.pre];
}
return result;
}
}
``````