title: Recursive Algorithm to find Combinations of a set in Java
body: <p>I was trying to find some examples on how to find a given set's (may be string or array of integers) all combinations in Java. And I have came across this code piece (found in <a href="http://introcs.cs.princeton.edu/java/23recursion/Combinations.java.html" rel="nofollow">http://introcs.cs.princeton.edu/java/23recursion/Combinations.java.html</a>. I have copied only the related parts in here.):</p>
  
  <pre><code>// print all subsets of the characters in s
  public static void comb1(String s) { comb1("", s); }
  
  // print all subsets of the remaining elements, with given prefix 
  private static void comb1(String prefix, String s) {
      if (s.length() &gt; 0) {
          System.out.println(prefix + s.charAt(0));
          comb1(prefix + s.charAt(0), s.substring(1));
          comb1(prefix,               s.substring(1));
      }
  }  
  
  // read in N from command line, and print all subsets among N elements
  public static void main(String[] args) {
     int N = Integer.parseInt(args[0]);
     String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
     String elements = alphabet.substring(0, N);
  
     // using first implementation
     comb1(elements);
     System.out.println();
  }
  </code></pre>
  
  <p>But, I really do not understand how it works. Does anyone care to explain?</p>