// CSE 143, Autumn 2013 // This program uses recursive backtracking to print 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 recursive helper to implement permute logic. // Adds a 'chosen' parameter representing all characters that // have been chosen so far. private static void permute(String s, String chosen) { if(s.length() == 0) { // Base case; all characters have been chosen. Print! System.out.println(chosen); } else { // Recursive case; s contains some characters to permute. // for each possible choice, for(int i = 0; i < s.length(); i++) { // choose a character from s (and remove it) char c = s.charAt(i); String rest = s.substring(0, i) + s.substring(i + 1); // explore permute(rest, chosen + c); // unchoose (nothing to do because we didn't modify s) } } } }