-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
43 lines (35 loc) · 1.19 KB
/
Permutations.java
File metadata and controls
43 lines (35 loc) · 1.19 KB
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
package String;
import java.util.*;
public class Permutations {
public static List<String> generateUniquePermutations(String str) {
List<String> result = new ArrayList<>();
char[] chars = str.toCharArray();
generateUniquePermutations(chars, 0, chars.length - 1, result);
return result;
}
public static void generateUniquePermutations(char[] chars, int start, int end, List<String> result) {
if (start == end) {
result.add(new String(chars));
return;
}
Set<Character> seen = new HashSet<>();
for (int i = start; i <= end; i++) {
if (!seen.contains(chars[i])) {
seen.add(chars[i]);
swap(chars, i, start);
generateUniquePermutations(chars, start + 1, end, result);
swap(chars, i, start);
}
}
}
public static void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
public List<String> find_permutation(String S) {
List<String> res = generateUniquePermutations(S);
Collections.sort(res);
return res;
}
}