File tree 3 files changed +102
-2
lines changed
3 files changed +102
-2
lines changed Original file line number Diff line number Diff line change 25
25
<!-- 这里可写当前语言的特殊实现逻辑 -->
26
26
27
27
``` python
28
-
28
+ class Solution :
29
+ def permutation (self , s : str ) -> List[str ]:
30
+ def dfs (x ):
31
+ if x == len (s) - 1 :
32
+ res.append(" " .join(chars))
33
+ return
34
+ t = set ()
35
+ for i in range (x, len (s)):
36
+ if chars[i] in t:
37
+ continue
38
+ t.add(chars[i])
39
+ chars[i], chars[x] = chars[x], chars[i]
40
+ dfs(x + 1 )
41
+ chars[i], chars[x] = chars[x], chars[i]
42
+ chars, res = list (s), []
43
+ dfs(0 )
44
+ return res
29
45
```
30
46
31
47
### Java
32
48
<!-- 这里可写当前语言的特殊实现逻辑 -->
33
49
34
50
``` java
35
-
51
+ class Solution {
52
+ private char [] chars;
53
+ private List<String > res;
54
+
55
+ public String [] permutation (String s ) {
56
+ chars = s. toCharArray();
57
+ res = new ArrayList<> ();
58
+ dfs(0 );
59
+ return res. toArray(new String [res. size()]);
60
+ }
61
+
62
+ private void dfs (int x ) {
63
+ if (x == chars. length - 1 ) {
64
+ res. add(String . valueOf(chars));
65
+ return ;
66
+ }
67
+ Set<Character > set = new HashSet<> ();
68
+ for (int i = x; i < chars. length; ++ i) {
69
+ if (set. contains(chars[i])) {
70
+ continue ;
71
+ }
72
+ set. add(chars[i]);
73
+ swap(i, x);
74
+ dfs(x + 1 );
75
+ swap(i, x);
76
+ }
77
+ }
78
+
79
+ private void swap (int i , int j ) {
80
+ char t = chars[i];
81
+ chars[i] = chars[j];
82
+ chars[j] = t;
83
+ }
84
+ }
36
85
```
37
86
38
87
### ...
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private char [] chars ;
3
+ private List <String > res ;
4
+
5
+ public String [] permutation (String s ) {
6
+ chars = s .toCharArray ();
7
+ res = new ArrayList <>();
8
+ dfs (0 );
9
+ return res .toArray (new String [res .size ()]);
10
+ }
11
+
12
+ private void dfs (int x ) {
13
+ if (x == chars .length - 1 ) {
14
+ res .add (String .valueOf (chars ));
15
+ return ;
16
+ }
17
+ Set <Character > set = new HashSet <>();
18
+ for (int i = x ; i < chars .length ; ++i ) {
19
+ if (set .contains (chars [i ])) {
20
+ continue ;
21
+ }
22
+ set .add (chars [i ]);
23
+ swap (i , x );
24
+ dfs (x + 1 );
25
+ swap (i , x );
26
+ }
27
+ }
28
+
29
+ private void swap (int i , int j ) {
30
+ char t = chars [i ];
31
+ chars [i ] = chars [j ];
32
+ chars [j ] = t ;
33
+ }
34
+ }
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def permutation (self , s : str ) -> List [str ]:
3
+ def dfs (x ):
4
+ if x == len (s ) - 1 :
5
+ res .append ("" .join (chars ))
6
+ return
7
+ t = set ()
8
+ for i in range (x , len (s )):
9
+ if chars [i ] in t :
10
+ continue
11
+ t .add (chars [i ])
12
+ chars [i ], chars [x ] = chars [x ], chars [i ]
13
+ dfs (x + 1 )
14
+ chars [i ], chars [x ] = chars [x ], chars [i ]
15
+ chars , res = list (s ), []
16
+ dfs (0 )
17
+ return res
You can’t perform that action at this time.
0 commit comments