fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.stream.*;
  5. import java.util.stream.Collectors;
  6.  
  7. class Ideone
  8. {
  9. public static void main (String[] args) throws java.lang.Exception
  10. {
  11. String a = "ABC";
  12.  
  13. StringBuilder b = new StringBuilder();
  14.  
  15. List<String> combinations = new ArrayList<>();
  16.  
  17. combine(a, b, 0, 0, combinations);
  18.  
  19. List<String> filtered = combinations.stream()
  20.  
  21. .filter(t -> t.length() == 2)
  22.  
  23. .collect(Collectors.toList());
  24.  
  25.  
  26. filtered.stream()
  27.  
  28. .forEach(t -> {
  29.  
  30. List<String> permutations = new ArrayList<>();
  31.  
  32. StringBuilder sb = new StringBuilder();
  33.  
  34. boolean used[] = new boolean[2];
  35.  
  36. used[0] = false;
  37.  
  38. used[1] = false;
  39.  
  40. permute(t, sb, used, permutations);
  41.  
  42. for(String s: permutations){
  43.  
  44. System.out.println(s);
  45.  
  46. }
  47.  
  48. });
  49.  
  50. }
  51.  
  52. public static void combine(String a, StringBuilder b, int start, int level, List<String> combinations) {
  53.  
  54. for (int i = start; i < a.length(); i++) {
  55.  
  56. if (b.toString().contains(String.valueOf(a.charAt(i))) == false) {
  57.  
  58. b.append(a.charAt(i));
  59.  
  60. combinations.add(b.toString());
  61.  
  62. if (i < a.length() - 1) {
  63.  
  64. combine(a, b, start + 1, level + 1, combinations);
  65.  
  66. }
  67.  
  68. b.setLength(b.length() - 1);
  69.  
  70. }
  71.  
  72. }
  73.  
  74. }
  75.  
  76. public static void permute(String a, StringBuilder b, boolean[] used, List<String> permutations) {
  77.  
  78. if ( b.length() == a.length()) {
  79.  
  80. permutations.add(b.toString());
  81.  
  82. return;
  83. }
  84.  
  85. for (int i = 0; i < a.length(); i++) {
  86.  
  87. if (used[i]) {continue;}
  88.  
  89. used[i] = true;
  90.  
  91. b.append(a.charAt(i));
  92.  
  93. permute(a, b, used, permutations);
  94.  
  95. b.setLength(b.length()-1);
  96.  
  97. used[i] = false;
  98.  
  99. }
  100.  
  101. }
  102.  
  103. }
  104.  
Success #stdin #stdout 0.08s 34248KB
stdin
Standard input is empty
stdout
AB
BA
AC
CA
BC
CB