// Erika Wolfe, CSE 143 // Examples of recursive backtracking import java.util.*; public class Backtracking { public static void main(String[] args) { fourAB(); System.out.println(); diceRoll(3); System.out.println(); diceSum(2, 7); } // 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 { fourAB(soFar + "a"); // no need to unchoose because soFar + "a" returns a new String 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 the dice in chosen // as the prefix. 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 (1-6) chosen.add(i); // choose diceRoll(dice - 1, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose // unchoose is necessary because all recursive calls have a // reference to the same list } } } // Prints all possible outcomes of rolling the given // number of six-sided dice that add up to exactly // the given sum, in [#, #, #] format. public static void diceSum(int dice, int sum) { diceSum(dice, sum, 0, new ArrayList()); } // Prints all the possible outcomes of rolling the given number // of six-sided dice that add up to exactly the given sum, in [#, #, #] format. // sumSoFar is the sum of all the numbers in chosen. chosen is // the prefix for all the answers printed. private static void diceSum(int dice, int sum, int sumSoFar, List chosen) { if (dice == 0 && sumSoFar == sum) { System.out.println(chosen); } else if (sumSoFar <= sum) { // needs to be else if - otherwise continues recursing // when dice is negative if base case wasn't hit for (int i = 1; i <= 6; i++) { // for all possible choices chosen.add(i); // choose diceSum(dice - 1, sum, sumSoFar + i, chosen); // explore chosen.remove(chosen.size() - 1); // unchoose } } } }