// Hunter Schafer, CSE 143 // Examples of recursive backtracking import java.util.*; public class Backtracking2 { public static void main(String[] args) { diceSum(2, 7); } // 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 + dice <= sum && sumSoFar + 6 * dice >= sum) { // The check above makes sure // 1. The sum is attainable from sumSoFa // 2. We won't overshoot the target sum with the number of dice remaining 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 } } } }