// CSE 143, Winter 2009, Marty Stepp // This program import java.util.*; // for Random public class Permutations { public static void main(String[] args) { permute("MARTY"); } public static void permute(String s) { permute(s, ""); } private static void permute(String s, String chosen) { // debug println to watch the stack of calls // Recursion.println("permute(" + s + ", " + chosen + ")"); if (s.length() == 0) { // base case: no letters left to choose from System.out.println(chosen); } else { // recursive case: must choose a letter and permute the rest for (int i = 0; i < s.length(); i++) { // "make a choice" (pull out a letter from the string) String letter = s.substring(i, i + 1); // "R" s = s.substring(0, i) + s.substring(i + 1, s.length()); // "MATY" // explore the rest (all permutations that start with letter) permute(s, chosen + letter); // "un-make the choice" (put the letter back into the string) s = s.substring(0, i) + letter + s.substring(i, s.length()); } } } }