Share Pastebin
Guest
Public paste!

Ray

By: a guest | Apr 8th, 2008 | Syntax: Java | Size: 0.62 KB | Hits: 389 | Expires: Never
This paste has a previous version, view the difference. Copy text to clipboard
  1. // Return a list of all the subsequences of `li' with length `n'.
  2. // http://cadrlife.blogspot.com/2008/03/returning-considered-difficult.html
  3.  
  4. private static <T> List<List<T>> subn(int n, List<T> li) {
  5.     if (n == 0) {
  6.         return Collections.<List<T>>singletonList(new ArrayList<T>());
  7.     }
  8.     if (li.isEmpty()) {
  9.         return new ArrayList<List<T>>();
  10.     }
  11.     List<List<T>> ret = new ArrayList<List<T>>();
  12.     T x = li.get(0);
  13.     List<T> xs = li.subList(1, li.size());
  14.     for (List<T> sub : subn(n-1, xs)) {
  15.         sub.add(0, x);
  16.         ret.add(sub);
  17.     }
  18.     ret.addAll(subn(n, xs));
  19.     return ret;
  20. }