File tree Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Expand file tree Collapse file tree 2 files changed +53
-0
lines changed Original file line number Diff line number Diff line change @@ -10,6 +10,8 @@ leetcode 测试
10
10
11
11
##### 包含的内容如下
12
12
13
+ https://leetcode.cn/problems/tree-of-coprimes/
14
+
13
15
https://leetcode.cn/problems/check-if-all-characters-have-equal-number-of-occurrences/
14
16
15
17
https://leetcode.cn/problems/cyJERH/
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments