Comb2.java


Below is the syntax highlighted version of Comb2.java from §2.3 Recursion.


/******************************************************************************
 *  Compilation:  javac Comb2.java
 *  Execution:    java Comb2 n k
 *  
 *  Enumerates all subsets of size k on n elements.
 *
 *  % java Comb2 5 3
 *  0 1 2 
 *  0 1 3 
 *  0 1 4 
 *  0 2 3 
 *  0 2 4 
 *  0 3 4 
 *  1 2 3 
 *  1 2 4 
 *  1 3 4 
 *  2 3 4 
 *
 ******************************************************************************/

public class Comb2 {

    private static void showCombination(int[] s) {
        for (int i = 0; i < s.length; i++)
            StdOut.print(s[i] + " ");
        StdOut.println();
    }

    public static void generate(int[] s, int position, int nextInt, int k, int n) {
        if (position == k) {
            showCombination(s);
            return;
        }
        for (int i = nextInt; i < n; i++) {
            s[position] = i;
            generate(s, position + 1, i + 1, k, n);
        }
    }  

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        int k = Integer.parseInt(args[1]);

        int[] s = new int[k];
        generate(s, 0, 0, k, n);
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.