Ray
By: a guest | Apr 8th, 2008 | Syntax:
Java | Size: 0.62 KB | Hits: 389 | Expires: Never
// Return a list of all the subsequences of `li' with length `n'.
// http://cadrlife.blogspot.com/2008/03/returning-considered-difficult.html
private static <T> List<List<T>> subn(int n, List<T> li) {
if (n == 0) {
return Collections.
<List
<T
>>singletonList
(new ArrayList
<T
>());
}
if (li.isEmpty()) {
return new ArrayList<List<T>>();
}
List<List<T>> ret = new ArrayList<List<T>>();
T x = li.get(0);
List<T> xs = li.subList(1, li.size());
for (List<T> sub : subn(n-1, xs)) {
sub.add(0, x);
ret.add(sub);
}
ret.addAll(subn(n, xs));
return ret;
}