publicclassLargestDivisibleSubset{ /** * 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: * * Input: [1,2,3] * Output: [1,2] (of course, [1,3] will also be ok) * Example 2: * * Input: [1,2,4,8] * Output: [1,2,4,8] */ public List<Integer> largestDivisibleSubset(int[] nums){
int n = nums.length; int dp[] = newint[n]; int ptr[] = newint[n];
for (int i=0; i<ptr.length; i++){ ptr[i] = -1; }
List<Integer> res = new ArrayList<>();
int idx=0; Arrays.sort(nums);
for (int i=1; i<nums.length; i++){ for (int j=0; j<i; j++){ if (nums[i] % nums[j]==0){ dp[i] = dp[j] + 1; ptr[i] = j; if (dp[i] > dp[idx]){ idx = i; } } } }