class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<>();
if (nums == null || nums.length < 1) return res;
int len = nums.length;
Arrays.sort(nums);
int[] dp = new int[len];
int[] pre = new int[len];
int max = 1;
int maxIdx = 0;
dp[0] = 1;
pre[0] = -1;
for (int i = 1; i < len; i++) {
pre[i] = -1;
dp[i] = 1;
for (int j = i - 1; j >= 0; j--) {
if (nums[i] % nums[j] == 0) {
//dp[i] = Math.max(dp[i], dp[j] + 1);
if (dp[j] + 1 > dp[i]) {
pre[i] = j;
dp[i] = dp[j] + 1;
}
}
}
if (dp[i] >= max) {
max = dp[i];
maxIdx = i;
}
}
Integer[] ans = new Integer[max];
while (maxIdx != -1) {
ans[--max] = nums[maxIdx];
maxIdx = pre[maxIdx];
}
return Arrays.asList(ans);
}
}