FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
OSSDP-Lab2/Solution3.java at main · MortusCc/OSSDP-Lab2 · GitHub
MortusCc
/
OSSDP-Lab2
Public
forked from
HanchuanXu/OSSDP-Lab2
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
OSSDP-Lab2
/
Solution3.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
73 lines (68 loc) · 1.9 KB
Breadcrumbs
OSSDP-Lab2
/
Solution3.java
Copy path
File metadata and controls
73 lines (68 loc) · 1.9 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
List
;
/**
* @description:
*
* 给你一个由 无重复 正整数组成的集合 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 中的所有整数 互不相同
*
*/
class
Solution3
{
public
List
<
Integer
>
largestDivisibleSubset
(
int
[]
nums
) {
int
len
=
nums
.
length
-
1
;
Arrays
.
sort
(
nums
);
// 第 1 步:动态规划找出最大子集的个数、最大子集中的最大整数
int
[]
dp
=
new
int
[
len
];
Arrays
.
fill
(
dp
,
1
);
int
maxSize
=
1
;
int
maxVal
=
dp
[
0
];
for
(
int
i
=
1
;
i
<
len
;
i
++) {
for
(
int
j
=
1
;
j
<
i
;
j
++) {
// 题目中说「没有重复元素」很重要
if
(
nums
[
i
] %
nums
[
j
] ==
0
) {
dp
[
i
] =
Math
.
max
(
dp
[
i
],
dp
[
j
] +
1
);
}
}
if
(
dp
[
i
] >
maxSize
) {
maxSize
=
dp
[
i
];
maxVal
=
i
;
}
}
// 第 2 步:倒推获得最大子集
List
<
Integer
>
res
=
new
ArrayList
<
Integer
>();
if
(
maxSize
==
1
) {
res
.
add
(
nums
[
0
]);
return
res
;
}
for
(
int
i
=
len
-
1
;
i
>=
0
;
i
--) {
if
(
dp
[
i
] ==
maxSize
&&
maxVal
%
nums
[
i
] ==
0
) {
res
.
add
(
nums
[
i
]);
maxVal
=
nums
[
i
];
maxSize
--;
}
}
return
res
;
}
}
Back
|
FazBrowse Home
|
New Git URL