title: Algorithm to get all the combinations of size n from an array (Java)?
body: <p>Right now I'm trying to write a function that takes an array and an integer n, and gives a list of each size n combination (so a list of int arrays). I am able to write it using n nested loops, but this only works for a specific size of subset. I can't figure out how to generalize it to work for any size of combination. I think I need to use recursion?</p>
  
  <p>This is the code for all combinations of 3 elements, and I need an algorithm for any number of elements.</p>
  
  <pre><code>import java.util.List;
  import java.util.ArrayList;
  
  public class combinatorics{
      public static void main(String[] args) {
  
          List&lt;int[]&gt; list = new ArrayList&lt;int[]&gt;();
          int[] arr = {1,2,3,4,5};
          combinations3(arr,list);
          listToString(list);
      }
  
      static void combinations3(int[] arr, List&lt;int[]&gt; list){
          for(int i = 0; i&lt;arr.length-2; i++)
              for(int j = i+1; j&lt;arr.length-1; j++)
                  for(int k = j+1; k&lt;arr.length; k++)
                      list.add(new int[]{arr[i],arr[j],arr[k]});
      }
  
      private static void listToString(List&lt;int[]&gt; list){
          for(int i = 0; i&lt;list.size(); i++){ //iterate through list
              for(int j : list.get(i)){ //iterate through array
                  System.out.printf("%d ",j);
              }
          System.out.print("\n");
          }
      }
  }
  </code></pre>