forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation.java
More file actions
45 lines (37 loc) · 944 Bytes
/
Permutation.java
File metadata and controls
45 lines (37 loc) · 944 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
36
37
38
39
40
41
42
43
44
45
package misc;
public class Permutation {
private static int solutions = 0;
public static void main(String[] args) {
String str = "12345678";
perm(str);
System.out.println(solutions);
}
public static void perm(String str) {
perm("", str);
}
private static void perm(String prefix, String remainder) {
if (0 == remainder.length()) {
if (check(prefix)) {
solutions++;
System.out.println(prefix);
}
return;
} else {
for (int i = 0; i < remainder.length(); i++) {
perm(prefix + remainder.substring(i, i + 1),
remainder.substring(0, i) + remainder.substring(i + 1));
}
}
}
private static boolean check(String prefix) {
for (int i = 0; i < prefix.length(); i++) {
for (int j = i + 1; j < prefix.length(); j++) {
if ((j - i == prefix.charAt(j) - prefix.charAt(i))
|| (j - i == prefix.charAt(i) - prefix.charAt(j))) {
return false;
}
}
}
return true;
}
}