友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
368. 最大整除子集
给你一个由 无重复 正整数组成的集合 nums
,请你找出并返回其中最大的整除子集 answer
,子集中每一元素对 (answer[i], answer[j])
都应当满足:
-
answer[i] % answer[j] == 0
,或 -
answer[j] % answer[i] == 0
如果存在多个有效解子集,返回其中任何一个均可。
示例 1:
输入:nums = [1,2,3] 输出:[1,2] 解释:[1,3] 也会被视为正确答案。
示例 2:
输入:nums = [1,2,4,8] 输出:[1,2,4,8]
提示:
-
1 <= nums.length <= 1000
-
1 <= nums[i] <= 2 * 109
-
nums
中的所有整数 互不相同
思路分析
动态规划!可以转化成最长子序列!
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-07-22 21:04:16
*/
public List<Integer> largestDivisibleSubset(int[] nums) {
Arrays.sort(nums);
int n = nums.length;
int[] lens = new int[n];
int[] idx = new int[n];
for (int i = 0; i < n; i++) {
// 至少包含自身一个数,因此起始长度为 1,由自身转移而来
int l = 1, p = i;
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0) {
// 如果能接在更长的序列后面,则更新「最大长度」&「从何转移而来」
if (lens[j] + 1 > l) {
l = lens[j] + 1;
p = j;
}
}
}
// 记录「最终长度」&「从何转移而来」
idx[i] = p;
lens[i] = l;
}
// 遍历所有的 lens[i],取得「最大长度」和「对应下标」
int max = -1, index = -1;
for (int i = 0; i < n; i++) {
if (lens[i] > max) {
max = lens[i];
index = i;
}
}
// 使用 idx[] 数组回溯出具体方案
List<Integer> result = new ArrayList<>();
while (result.size() < max) {
result.add(nums[index]);
index = idx[index];
}
return result;
}