-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.java
More file actions
65 lines (55 loc) · 1.65 KB
/
Permutations.java
File metadata and controls
65 lines (55 loc) · 1.65 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//Problem
//
// A permutation of length n
// n
// is an ordering of the positive integers {1,2,…,n}. For example, π=(5,3,2,1,4)
// is a permutation of length 5
//
// Given: A positive integer n≤7
//
// Return: The total number of permutations of length n, followed by a list of all such permutations (in any order).
//
// Sample Dataset
//
// 3
// Sample Output
//
// 6
// 1 2 3
// 1 3 2
// 2 1 3
// 2 3 1
// 3 1 2
// 3 2 1
import java.util.ArrayList;
import java.util.List;
public class Permutations {
private Permutations() {
}
public static void permute(List<String> permutations, String prefix, String permString) {
int length = permString.length();
if (length == 0) {
permutations.add(prefix.replace("", " ").trim());
return;
}
for(int i=0; i<length; i++) {
permute(permutations, prefix + permString.charAt(i),
permString.substring(0, i) + permString.substring(i+1, length));
}
}
private static String getPermString(int perm) {
StringBuilder permString = new StringBuilder();
for (int i = 1; i <= perm; i++) {
permString.append(i);
}
return permString.toString();
}
public static void main(String[] args) {
int perm = 5;
List<String> permutations = new ArrayList<>();
permute(permutations, "", getPermString(perm));
System.out.println(permutations.size());
permutations.forEach(System.out::println);
assert(permutations.size() == 6);
}
}