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:
Example 2:
分析
這里需要發(fā)現(xiàn)一個規(guī)律侵贵,就是如果result中已經(jīng)有【1扎瓶,2】,那么對于要新加進來的數(shù)刽沾,只要它能整除掉result中最大的數(shù)就可以缀蹄,因為如果先把result按大小排序峭跳,那么顯然result中最大的數(shù)可以整除其他比他小的數(shù),那么新加來的數(shù)都可以整除最大的數(shù)缺前,自然也可以其他數(shù)蛀醉。所以我們先將數(shù)組排序。然后用一個數(shù)組記錄添加的元素衅码,也就是類似記錄路徑拯刁,這種方法記錄路徑的方法很常用,類似于并查集中的應(yīng)用逝段。具體看代碼
代碼
public class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int n = nums.length;
int[] count = new int[n];
int[] pre = new int[n];
Arrays.sort(nums);
int max = 0, index = -1;
for (int i = 0; i < n; i++) {
count[i] = 1;
pre[i] = -1;
for (int j = i - 1; j >= 0; j--) {
if (nums[i] % nums[j] == 0) {
if (1 + count[j] > count[i]) {
count[i] = count[j] + 1;
pre[i] = j;
}
}
}
if (count[i] > max) {
max = count[i];
index = i;
}
}
List<Integer> res = new ArrayList<>();
while (index != -1) {
res.add(nums[index]);
index = pre[index];
}
return res;
}
}