// Hunter Schafer, CSE 143 // Examples of recursive backtracking import java.util.*; public class Backtracking { public static void main(String[] args) { fourAB(); diceRoll(3); } // This method will print all strings of length 4 composed of // only a's and b's public static void fourAB() { fourAB(""); } // Prints all strings of length 4 composed of only a's and b's // that start with the given prefix soFar private static void fourAB(String soFar) { if (soFar.length() == 4) { System.out.println(soFar); } else { // soFar = "a" // choose an "a", now result is "aa" fourAB(soFar + "a"); fourAB(soFar + "b"); } } // Prints all possible outcomes of rolling the given // number of six-sided dice in [#, #, #] format. // pre: dice >= 0 public static void diceRoll(int dice) { diceRoll(dice, new ArrayList()); } // Prints all possible outcomes of rolling the given number // of six-sided dice in [#, #, #] format with chosen // as the prefix of all printed. private static void diceRoll(int dice, List chosen) { if (dice == 0) { System.out.println(chosen); } else { for (int i = 1; i <= 6; i++) { // for all possible choices chosen.add(i); // choose diceRoll(dice - 1, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }