-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain38.java
More file actions
35 lines (31 loc) · 920 Bytes
/
Main38.java
File metadata and controls
35 lines (31 loc) · 920 Bytes
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
package JZOffer2;
import java.util.*;
public class Main38 {
Set<String> rec;
boolean[] visited;
public String[] permutation(String s) {
int n = s.length();
rec = new HashSet<>();
visited = new boolean[n];
char[] arr = s.toCharArray();
Arrays.sort(arr);
StringBuffer perm = new StringBuffer();
backtrack(arr, 0, n, perm);
return rec.stream().toArray(String[]::new);
}
private void backtrack(char[] arr, int i, int n, StringBuffer perm) {
if(i == n){
rec.add(perm.toString());
return;
}
for (int j = 0; j < n; j++) {
if(!visited[j]){
visited[j] = true;
perm.append(arr[j]);
backtrack(arr, i+1, n, perm);
perm.deleteCharAt(perm.length() - 1);
visited[j] = false;
}
}
}
}