// CSE 143, Winter 2010, Marty Stepp // This program uses recursive backtracking to print all permutations // (all possible arrangements of letters) of a given string. public class Permutations { public static void main(String[] args) { permute("MARTY"); System.out.println(); permute("JANE"); } // Prints all possible permutations of letters of the given string, // one per line. For example, permute("MARTY") prints MARTY, MATRY, // ATRMY, YARMT, etc. Uses backtracking to generate permutations. // Precondition: s is not null (throws NullPointerException if so) public static void permute(String s) { // parameters desired: // 1. letters available to choose // 2. letters we already have chosen permute(s, ""); } // Recursive helper method for choosing letters and backtracking. // Additional 'chosen' parameter stores the letters we have picked so far. private static void permute(String s, String chosen) { // uncomment the following line to see the recursive calls // Recursion.println("permute " + s + " " + chosen); if (s.length() == 0) { // base case: all letters have been chosen. Print the chosen word System.out.println(chosen); } else { // for each possible next letter to try, ... for (int i = 0; i < s.length(); i++) { // choose char c = s.charAt(i); s = s.substring(0, i) + s.substring(i + 1); // explore permute(s, chosen + c); // un-choose s = s.substring(0, i) + c + s.substring(i); } } } // permute("marty", "") // permute("arty", "m") // permute("rty", "ma") // permute("", "matry") --> matry }