import java.util.*; // Examples of recursive backtracking public class Backtracking { public static void main(String[] args) { // fourAB(); diceRoll(2); } // Prints 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 starting with the given prefix private static void fourAB(String soFar) { if (soFar.length() == 4) { // base case System.out.println(soFar); } else { // recursive case // choices: a, b 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(new ArrayList<>(), dice); } // 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(List chosen, int dice) { if (dice == 0) { // base case System.out.println(chosen); } else { // recursive case // choices: 1 - 6 for (int i = 1; i <= 6; i++) { // for each choice: chosen.add(i); // choose diceRoll(chosen, dice - 1); // explore chosen.remove(chosen.size() - 1); // unchoose // chosen.remove(i) does NOT work - we want to remove the // last thing (the choice we just added). A stack would be // even better than a list here! } } } }