// CSE 143, Winter 2010, Marty Stepp // An alternative implementation of the "subsets" problem // that uses lists rather than strings / chars to store choices. import java.util.*; public class Subsets { public static void main(String[] args) { List names = new LinkedList(); names.add("Janet"); names.add("Robert"); names.add("Morgan"); names.add("Char"); subsets(names); } // Prints all sub-lists of the given list of Strings. // Precondition: elements != null and elements contains no duplicates public static void subsets(List elements) { List chosen = new ArrayList(); explore(elements, chosen); } // Private recursive helper to explore all sub-lists of the given list of // elements, assuming the given list of strings have already been chosen. private static void explore(List elements, List chosen) { Recursion.println("explore choices=" + elements + ",chosen=" + chosen); if (elements.isEmpty()) { System.out.println(chosen); // base case; nothing left to choose } else { String first = elements.remove(0); // make a choice: 1st element // two explorations: one with this first element, one without explore(elements, chosen); // MRC, RC, MC, ... chosen.add(first); explore(elements, chosen); // JMRC, JRC, JMC, ... chosen.remove(chosen.size() - 1); elements.add(0, first); // backtrack! put 1st element back } } }