Java tutorial
//package com.java2s; //License from project: Creative Commons License import java.util.ArrayList; import java.util.List; import java.util.Set; public class Main { private static <T> void computeAllItemCombinationsRecursive(T[] input, Set<List<T>> output, List<T> combination, int pos, int maxLength) { if (pos == input.length && combination.size() == maxLength) { output.add(combination); } if (pos < input.length) { if (combination != null) { combination.add(input[pos]); if (combination.size() == maxLength) { output.add(combination); } else { for (int i = pos; i < input.length; ++i) { computeAllItemCombinationsRecursive(input, output, combination, i + 1, maxLength); } } } int lastPosToStartFrom = input.length - maxLength + 1; for (int i = pos; i < lastPosToStartFrom; ++i) { combination = new ArrayList<>(maxLength); combination.add(input[pos]); computeAllItemCombinationsRecursive(input, output, combination, i + 1, maxLength); } } } }