-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAllPermutationsOfAString.java
More file actions
40 lines (35 loc) · 1.17 KB
/
AllPermutationsOfAString.java
File metadata and controls
40 lines (35 loc) · 1.17 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
/**
* Java program to find all the permutations of a given String using recursion.
* For example, given a String "XYZ", this program will print
* all 6 possible permutations of
* input e.g. XYZ, XZY, YXZ, YZX, ZXY, XYX
*
* @author Javin Paul
*/
public class AllPermutationsOfAString {
public static void main(String args[]) {
permutation("123");
}
/*
* A method exposed to client to calculate permutation of String in Java.
*/
public static void permutation(String input){
permutation("", input);
}
/*
* Recursive method which actually prints all permutations
* of given String, but since we are passing an empty String
* as current permutation to start with,
* I have made this method private and didn't expose it to client.
*/
private static void permutation(String perm, String word) {
if (word.isEmpty()) {
System.err.println(perm + word);
} else {
for (int i = 0; i < word.length(); i++) {
permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}
}
}
}