// Allison Obourn // CSE 143 - lecture 18 // 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, ""); } // Outputs all permutations of a string private static void permute(String s, String chosen) { if(s.length() == 0) { System.out.println(chosen); } 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 c = s.charAt(i); // chosen += c; // explicit "choose" String temp = s.substring(0, i) + s.substring(i + 1); permute(temp, chosen + c); // explicit unchoose if we modify chosen and s: // s = s.substring(0, i) + c + s.substring(i); // chosen = chosen.substring(0, chosen.length() - 1); } } } }