原题链接在这里:https://leetcode.com/problems/largest-divisible-subset/description/
题目:
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]
题解:
求最长的subset, subset中每两个数大的除以小的余数是0. 储存到当前点, 包括当前点, 符合要求的最大subset长度.
Let count[i] denotes largest subset ending with i.
For all j < i, if nums[i] % nums[j] == 0, then i could be added after j and may construct a largeer subset. Update count[i].
But how to get the routine. Use preIndex[i] denotes the pre index of i in the largest subset. Then could start with last index and get pre num one by one.
Time Complexity: O(n^2). n = nums.length.
Space: O(n).
AC Java:
1 class Solution { 2 public List<Integer> largestDivisibleSubset(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 5 if(nums == null || nums.length == 0){ 6 return res; 7 } 8 9 int len = nums.length; 10 Arrays.sort(nums); 11 int [] count = new int[len]; 12 int [] preIndex = new int[len]; 13 int resCount = 0; 14 int resIndex = -1; 15 16 for(int i = 0; i<len; i++){ 17 count[i] = 1; 18 preIndex[i] = -1; 19 for(int j = 0; j<i; j++){ 20 if(nums[i]%nums[j] == 0 && count[j]+1 > count[i]){ 21 count[i] = count[j]+1; 22 preIndex[i] = j; 23 } 24 } 25 26 if(resCount < count[i]){ 27 resCount = count[i]; 28 resIndex = i; 29 } 30 } 31 32 while(resIndex != -1){ 33 res.add(0, nums[resIndex]); 34 resIndex = preIndex[resIndex]; 35 } 36 37 return res; 38 } 39 }