// Zorah Fung, CSE 143 // Examples of recursive backtracking import java.util.*; public class Backtracking { public static void main(String[] args) { allABStrings(4); diceRoll(3); diceSum(3, 7); diceSum(5, 7); diceSum(15, 87); } // Prints all strings of length n composed of A's and B's // pre: n >= 0 public static void allABStrings(int n) { allABStrings(n, ""); } private static void allABStrings(int n, String result) { if (result.length() == n) { System.out.println(result); } else { allABStrings(n, result + "a"); allABStrings(n, result + "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()); } private static void diceRoll(int dice, List soFar) { if (dice == 0) { System.out.println(soFar); } else { for (int i = 1; i <= 6; i++) { soFar.add(i); diceRoll(dice - 1, soFar); soFar.remove(soFar.size() - 1); } } } // 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, new ArrayList(), 0); } private static void diceSum(int dice, int sum, List soFar, int sumSoFar) { if (dice == 0) { // int sumSoFar = 0; // for (int value : soFar) { // sumSoFar += value; // } if (sumSoFar == sum) { System.out.println(soFar); } } else if (sumSoFar + 6 * dice >= sum && sumSoFar + dice <= sum) { for (int i = 1; i <= 6; i++) { soFar.add(i); diceSum(dice - 1, sum, soFar, sumSoFar + i); soFar.remove(soFar.size() - 1); } } } }