Skip to content

Commit 56782a4

Browse files
committed
https://leetcode.cn/problems/tree-of-coprimes/
1 parent edc846a commit 56782a4

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/tree-of-coprimes/
14+
1315
https://leetcode.cn/problems/check-if-all-characters-have-equal-number-of-occurrences/
1416

1517
https://leetcode.cn/problems/cyJERH/

tree-of-coprimes/index.ts

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
export default getCoprimes;
2+
function getCoprimes(nums: number[], edges: number[][]): number[] {
3+
const edge = Array(nums.length)
4+
.fill(0)
5+
.map(() => Array<number>());
6+
for (const [a, b] of edges) {
7+
edge[a].push(b);
8+
edge[b].push(a);
9+
}
10+
11+
if (prime.length === 0) {
12+
for (const i of Array(51).keys()) {
13+
prime[i] = Array(51).fill(false);
14+
}
15+
16+
for (const i of Array(51).keys())
17+
for (let j = i; j < 51; j++) {
18+
prime[i][j] = prime[j][i] = greatestCommonDivisor(i, j) === 1;
19+
}
20+
}
21+
22+
const visited = new Set<number>();
23+
function dfs(node: number, ancestors: number[]) {
24+
if (!visited.has(node)) {
25+
visited.add(node);
26+
27+
if (ancestors.length) {
28+
for (let i = ancestors.length - 1; i >= 0; i--) {
29+
if (prime[nums[node]][nums[ancestors[i]]]) {
30+
results[node] = ancestors[i];
31+
break;
32+
}
33+
}
34+
}
35+
for (const child of edge[node]) {
36+
ancestors.push(node);
37+
dfs(child, ancestors);
38+
ancestors.pop();
39+
}
40+
}
41+
}
42+
const results: number[] = Array(nums.length).fill(-1);
43+
dfs(0, []);
44+
return results;
45+
}
46+
47+
const prime: boolean[][] = [];
48+
49+
function greatestCommonDivisor(a: number, b: number): number {
50+
return b != 0 ? greatestCommonDivisor(b, a % b) : a;
51+
}

0 commit comments

Comments
 (0)