0%

June Leetcoding Challenge(6.13)

LeetCode六月挑战(6.13)Largest Divisible Subset Solution解题方案

Largest Divisible Subset

Solution
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.

1
2
3
4
5
6
7
8
Example 1:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]

思路

这道题有一个数学思路在里面
对于一个有序数组,插入的数如果能整除数组中最大的数,那么也可以整除数组中其他的数。
因此我们要先将数组排序,然后设置一个路径储存数组记录添加元素的路径。

Java代码

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
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
int[] count = new int[n];
int[] road = new int[n];
int max = 0, index = -1;
for (int i = 0; i < n; i++) {
count[i] = 1;
road[i] = -1;
for (int j = i - 1; j >= 0; j--) {
if (nums[i] % nums[j] == 0) {
if (count[i] < 1 + count[j]) {
count[i] = count[j] + 1;
road[i] = j;
}
}
}
if (count[i] > max) {
max = count[i];
index = i;
}
}
List<Integer> result = new ArrayList<>();
while (index != -1) {
result.add(nums[index]);
index = road[index];
}
return result;
}
}
-------------本文结束感谢您的阅读-------------

本文标题:June Leetcoding Challenge(6.13)

文章作者:Jungle

发布时间:2020年06月13日 - 12:07

最后更新:2020年06月13日 - 12:07

原始链接:http://yoursite.com/2020/06/13/LeetCodeJuneChallenge13th/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Welcome to my other publishing channels