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.
关键点是若b>a且b%a==0, c>b且c%b==0那么c%a==0
用dp保存在当前数字之前与当前数字符合条件的list。
public class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { if (nums.length == 0) { return new ArrayList<Integer>(); } Arrays.sort(nums); List<Integer>[] dp = new List[nums.length]; int resultIndex = 0; for (int i = 0; i < nums.length; i++) { List<Integer> curMax = new ArrayList<Integer>(); for (int j = 0; j < i; j++) { if (nums[i] % nums[j] == 0) { System.out.println(j); List<Integer> tmp = new ArrayList<Integer>(dp[j]); tmp.add(nums[i]); curMax = curMax.size() > tmp.size() ? curMax : tmp; } } // this number does not have any matched number yet, put this number into // the list so that it will be included in the following matches if (curMax.size() == 0) { curMax.add(nums[i]); } dp[i] = curMax; if (curMax.size() > dp[resultIndex].size()) { resultIndex = i; } } return dp[resultIndex]; } }