Given a set ofdistinct positiveintegers, find the largest subset such that every pair(Si, Sj)of elements in this subset satisfies:Si % Sj = 0orSj % Si = 0.
Notice
If there are multiple solutions, return any subset is fine.
publicList<Integer>largestDivisibleSubset(int[] nums) {List<Integer> res =newArrayList<>();if (nums ==null||nums.length==0) {return res; }int n =nums.length;// sort the array for easy divisionArrays.sort(nums);int[] dp =newint[n];int[] parent =newint[n];// use to track where this comes from// initialize dp array, every one can be divided by itself so fill with 1Arrays.fill(dp,1);// fill dp matrix when you can divide, just LISfor (int i =0; i < n; i++) {// can init the dp[i] = 1 here instead to use Arrays.fillfor (int j =0; j < i; j++) {if (nums[i] % nums[j] ==0&& (dp[j] +1) > dp[i]) { dp[i] =Math.max(dp[i], dp[j] +1); parent[i] = j; } } }// find longestint maxcnt =0;int maxInd =0;for (int i =0; i < n; i++) {if (dp[i] > maxcnt) { maxcnt = dp[i]; maxInd = i; } }// collect nums into resfor (int i =0; i < maxcnt; i++) {res.add(nums[maxInd]); maxInd = parent[maxInd]; }return res;}