// Zorah Fung, CSE143 // Demonstrates an exhaustive search algorithm by generating all permutations of // a given string. public class Permutations { public static void main(String[] args) { permute("team"); } // Outputs all permutations of the given string, one per line. // For example, TEAM can be permuted into MEAT, META, TMEA, ... public static void permute(String s) { permute(s, ""); } private static void permute(String s, String soFar) { if (s.length() == 0) { System.out.println(soFar); } else { for (int i = 0; i < s.length(); i++) { // when we use primitive types or Strings, we can choose and // unchoose simply by passing a copy of the value to recursive // calls. char chosen = s.charAt(i); String remaining = s.substring(0, i) + s.substring(i + 1); // soFar = soFar + chosen; // explicit "choose" permute(remaining, soFar + chosen); // explicit unchoose if we modify soFar and s: // soFar = soFar.substring(0, soFar.length() - 1); // s = s.substring(0, i) + chosen + s.substring(i); } } } }