Subsequence.java


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


/******************************************************************************
 *  Compilation:  javac Subsequence.java
 *  Execution:    java Subsequence s k
 *
 *  Print out all subsequences of the string s of length k.
 *
 *  % java Subsequence abcd 3
 *  abc
 *  abd
 *  acd
 *  bcd
 *
 *  % java Subsequence abcc 3
 *  abc
 *  abc
 *  acc
 *  bcc
 *
 ******************************************************************************/

public class Subsequence { 

    public static void print(String prefix, String remaining, int k) {
        if (k == 0) {
            StdOut.println(prefix);
            return;
        }
        if (remaining.length() == 0) return;
        print(prefix + remaining.charAt(0), remaining.substring(1), k-1);
        print(prefix, remaining.substring(1), k);
    }


    public static void main(String[] args) { 
        String s = args[0];
        int k = Integer.parseInt(args[1]);
        print("", s, k);
    }

}


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