fork(4) download
  1. /* All Permutations of a String */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Complexity O(n*n!) */
  8. class Ideone
  9. {
  10. public static ArrayList<String> strPerm(String str, ArrayList<String> list){
  11. int len = str.length();
  12. if(len==1){
  13. list.add(str);
  14. return list;
  15. }
  16.  
  17. list = strPerm(str.substring(0,len-1),list);
  18. int ls = list.size();
  19. char ap = str.charAt(len-1);
  20. for(int i=0;i<ls;i++){
  21. String temp = list.get(i);
  22. int tl = temp.length();
  23. for(int j=0;j<=tl;j++){
  24. list.add(temp.substring(0,j)+ap+temp.substring(j,tl));
  25. }
  26. }
  27.  
  28. while(true){
  29. String temp = list.get(0);
  30. if(temp.length()<len)
  31. list.remove(temp);
  32. else
  33. break;
  34. }
  35.  
  36. return list;
  37. }
  38.  
  39. public static void main (String[] args) throws java.lang.Exception
  40. {
  41. String str = "abc";
  42. ArrayList<String> list = new ArrayList<>();
  43.  
  44. list = strPerm(str,list);
  45. System.out.println("Total Permutations : "+list.size());
  46. for(int i=0;i<list.size();i++)
  47. System.out.println(list.get(i));
  48.  
  49. }
  50. }
Success #stdin #stdout 0.08s 381248KB
stdin
Standard input is empty
stdout
Total Permutations : 6
cba
bca
bac
cab
acb
abc