给出一个由无重复的正整数组成的集合, 找出其中最大的整除子集, 子集中任意一对 (Si, Sj) 都要满足: Si % Sj = 0 或 Sj % Si = 0。
如果有多个目标子集,返回其中任何一个均可。
示例 1:
集合: [1,2,3] 结果: [1,2] (当然, [1,3] 也正确)
示例 2:
集合: [1,2,4,8] 结果: [1,2,4,8]
变种最长路+hash
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
public class Main {
public static void main(String[] args) throws Exception {
int[] nums = {2, 3, 4, 8};
System.out.println(new Solution().largestDivisibleSubset(nums));
}
}
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<Integer>();
}
Map<Integer, Integer> hash = new HashMap<Integer, Integer>();
Map<Integer, Integer> hashRe = new HashMap<Integer, Integer>();
int idx = 0;
for (int num : nums) {
if (!hash.containsKey(num)) {
hash.put(num, ++idx);
hashRe.put(idx, num);
}
}
List<Integer>[] adj = new List[idx + 1];
for (int i = 0; i <= idx; i++) {
adj[i] = new ArrayList<Integer>();
}
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int min = Math.min(nums[i], nums[j]);
int max = Math.max(nums[i], nums[j]);
if (max % min == 0) {
adj[hash.get(min)].add(hash.get(max));
}
}
}
for (int i = 1; i <= idx; i++) {
adj[0].add(i);
}
return spfa(adj, hashRe);
}
List<Integer> spfa(List<Integer>[] adj, Map<Integer, Integer> hash) {
int n = adj.length + 1;
boolean[] inq = new boolean[n];
Arrays.fill(inq, false);
int[] dist = new int[n];
Arrays.fill(dist, Integer.MIN_VALUE);
int[] father = new int[n];
Arrays.fill(father, -1);
Queue<Integer> q = new LinkedList<Integer>();
q.add(0);
inq[0] = true;
dist[0] = 0;
while (!q.isEmpty()) {
int u = q.poll();
inq[u] = false;
for (int v : adj[u]) {
if (dist[u] + 1 > dist[v]) {
father[v] = u;
dist[v] = dist[u] + 1;
if (!inq[v]) {
inq[v] = true;
q.add(v);
}
}
}
}
int last = -1;
int maxd = -1;
for (int i = 1; i < n; i++) {
if (dist[i] > maxd) {
maxd = dist[i];
last = i;
}
}
List<Integer> res = new ArrayList<Integer>();
while (last != -1 && last != 0) {
res.add(hash.get(last));
last = father[last];
}
return res;
}
}