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]
Credits:
Special thanks to @Stomach_ache for adding this problem and creating all test cases.
1 public class Solution { 2 public List<Integer> largestDivisibleSubset(int[] nums) { 3 List<Integer> ans = new ArrayList<Integer>(); 4 if( nums.length == 0 || nums == null) return ans; 5 if(nums.length == 1){ 6 ans.add(nums[0]); 7 return ans; 8 } 9 Arrays.sort(nums);//先将数组排序之后再处理 10 int[] sum = new int[nums.length]; 11 int[] pre = new int[nums.length];//能被nums[i]整除的上一个数的索引 12 int max = 0, maxindex = 0; 13 for(int i = 0; i < nums.length; i++){ 14 sum[i] = 1; 15 pre[i] = -1; 16 for(int j = 0; j < i; j++){ 17 if(nums[i]%nums[j] == 0){ 18 pre[i] = j; 19 sum[i] = sum[j] + 1;// nums[i] % nums[j] 则sum[i] = sum[j] + 1 20 if(sum[i] > max){ 21 max = sum[i]; 22 maxindex = i; 23 } 24 } 25 } 26 } 27 while(maxindex != -1){//回溯,依次将数值加入ans 28 ans.add(nums[maxindex]); 29 maxindex = pre[maxindex]; 30 } 31 return ans; 32 } 33 }