Skip to content

Instantly share code, notes, and snippets.

@mmattozzi
Created February 3, 2011 19:58
Show Gist options
  • Save mmattozzi/810079 to your computer and use it in GitHub Desktop.
Save mmattozzi/810079 to your computer and use it in GitHub Desktop.
protected <T> List<List<T>> permutate(List<T> list) {
if (list == null) {
return null;
} else if (list.size() == 1) {
return Arrays.asList(list);
} else if (list.size() == 2) {
List<T> revList = new ArrayList<T>();
revList.addAll(list);
Collections.reverse(revList);
return Arrays.asList(list, revList);
} else {
List<List<T>> permutations = new ArrayList<List<T>>();
for (int i = 0; i < list.size(); i++) {
Collections.rotate(list, 1);
List<List<T>> permutated = permutate(list.subList(1, list.size()));
for (List<T> p : permutated) {
List<T> newP = new ArrayList<T>();
newP.add(list.get(0));
newP.addAll(p);
permutations.add(newP);
}
}
return permutations;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment