-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPermutationWithDuplicates.java
49 lines (39 loc) · 1.28 KB
/
PermutationWithDuplicates.java
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
44
45
46
47
48
49
package dynamic;
import java.util.*;
/**
* [Video](https://www.youtube.com/watch?v=JF4QrlUJItk)
*/
public class PermutationWithDuplicates {
public static void main(String[] args) {
List<String> result = new ArrayList<>();
String str = "aabc";
Map<Character, Integer> map = calculateFrequency(str);
printPerms(map, "", str.length(), result);
System.out.println(Arrays.toString(result.toArray()));
}
private static Map<Character, Integer> calculateFrequency(String str) {
Map<Character, Integer> map = new HashMap<>();
for (char c : str.toCharArray()) {
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
return map;
}
private static void printPerms(Map<Character, Integer> map, String prefix, int remaining, List<String> result) {
if (remaining == 0) {
result.add(prefix);
return;
}
for (Character c : map.keySet()) {
int count = map.get(c);
if (count > 0) {
map.put(c, count - 1);
printPerms(map, prefix + c, remaining - 1, result);
map.put(c, count);
}
}
}
}