Leetcode: Largest Divisible Subset

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]

DP Solution similar to Longest Increasing Subsequence:

我的解法:用一个arraylist存以某一个element结尾的最长sequence

 1 public class Solution {
 2     public List<Integer> largestDivisibleSubset(int[] nums) {
 3         List<Integer> res = new ArrayList<Integer>();
 4         if (nums==null || nums.length==0) return res;
 5         int[] dp = new int[nums.length];
 6         int maxdpIndex = 0;
 7         ArrayList<ArrayList<Integer>> records = new ArrayList<ArrayList<Integer>>();
 8         
 9         Arrays.sort(nums);
10         for (int i=0; i<nums.length; i++) {
11             dp[i] = 1;
12             ArrayList<Integer> record = new ArrayList<Integer>();
13             for (int j=0; j<i; j++) {
14                 if (nums[i] % nums[j] == 0) {
15                     if(dp[j] + 1 > dp[i]) {
16                         dp[i] = dp[j] + 1;
17                         record.clear();
18                         record.addAll(records.get(j));
19                     }
20                 }
21             }
22             record.add(nums[i]);
23             records.add(new ArrayList<Integer>(record));
24             if (dp[i] > dp[maxdpIndex]) maxdpIndex = i;
25         }
26         res = records.get(maxdpIndex);
27         return res;
28     }
29 }

别人的好方法,大体思路一样,只是不存arraylist, 而用一个preIndex数组存以某一个element结尾的最长sequence的上一个元素index, 这样做快了很多

 1 public class Solution {
 2     public List<Integer> largestDivisibleSubset(int[] nums) {
 3         int n = nums.length;
 4         int[] count = new int[n];
 5         int[] pre = new int[n];
 6         Arrays.sort(nums);
 7         int max = 0, index = -1;
 8         for (int i = 0; i < n; i++) {
 9             count[i] = 1;
10             pre[i] = -1;
11             for (int j = i - 1; j >= 0; j--) {
12                 if (nums[i] % nums[j] == 0) {
13                     if (1 + count[j] > count[i]) {
14                         count[i] = count[j] + 1;
15                         pre[i] = j;
16                     }
17                 }
18             }
19             if (count[i] > max) {
20                 max = count[i];
21                 index = i;
22             }
23         }
24         List<Integer> res = new ArrayList<>();
25         while (index != -1) {
26             res.add(nums[index]);
27             index = pre[index];
28         }
29         return res;
30     }
31 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/6105841.html