Lets see simple program to print all Permutations of given string using Recursion call.
OUTPUT:
import java.util.TreeSet; public class Permutation { static TreeSet<String> combination = new TreeSet<String>(); public static void main(String[] args) { String str = "ABCD"; permutation("", str); printAllCombination(); } private static void permutation(String prefix, String str) { int len = str.length(); if (len == 0) { combination.add(prefix); } else { for (int i = 0; i < len; i++) { String p = prefix + str.charAt(i); String s = str.substring(0, i) + str.substring(i + 1, len); permutation(p, s); } } } private static void printAllCombination() { int index = 0; for (String string : combination) { System.out.println(++index + "\t : " + string); } } }
OUTPUT:
1 : ABCD 2 : ABDC 3 : ACBD 4 : ACDB 5 : ADBC 6 : ADCB 7 : BACD 8 : BADC 9 : BCAD 10 : BCDA 11 : BDAC 12 : BDCA 13 : CABD 14 : CADB 15 : CBAD 16 : CBDA 17 : CDAB 18 : CDBA 19 : DABC 20 : DACB 21 : DBAC 22 : DBCA 23 : DCAB 24 : DCBA
No comments:
Write comments