Saturday, 15 August 2015

How to Find All Permutations of String in Java using Recursion

public class Permutations {

public static void main(String[] args) {
getPermutations("123");
}

public static void getPermutations(String str) {
getPermutations("", str);
}

private static void getPermutations(String prefix, String word) {

if (word == null || word.isEmpty()) {
System.out.println(prefix);
} else {
for (int i = 0; i < word.length(); i++) {
getPermutations(prefix + word.charAt(i), word.substring(0, i) + word.substring(i + 1));

}

}

}
}

No comments:

Post a Comment