forked from xiaoningning/java-algorithm-2010
-
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.74 KB
/
Permutations.java
File metadata and controls
65 lines (55 loc) · 1.74 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
import java.util.Scanner;
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) {
perm1("", s);
}
private static void perm1(String prefix, String s) {
// System.out.println("prefix: " + prefix);
// System.out.println("s: " + s);
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i + 1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length()-1;
/*
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
*/
char[] a = s.toCharArray();
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 0) {
System.out.println(a);
return;
}
for (int i = 0; i <= n; i++) {
swap(a, i, n - 1);
perm2(a, n - 1);
swap(a, i, n - 1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number: ");
int N = Integer.parseInt(s.nextLine());
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
perm1(elements);
System.out.println();
perm2(elements);
}
}