You can use simple backtracking to do this. You just go over each element and either pick this element to be in your subset or not. At the same time you can keep track of the current subset your are trying to build (current_subset
) and how many elements you can still pick (k
). A sample implementation:
static <E> void backtrack(int index, int k, Deque<E> current_subset,
List<E> elements)
{
if (k == 0) {
System.out.println(current_subset);
return;
}
if (index == elements.size())
return;
current_subset.push(elements.get(index));
backtrack(index + 1, k - 1, current_subset, elements);
current_subset.pop();
backtrack(index + 1, k, current_subset, elements);
}
backtrack(0, 2, new ArrayDeque<Integer>(),
Arrays.asList(new Integer[]{0, 1, 2, 3, 4}));
/*
[1, 0]
[2, 0]
[3, 0]
[4, 0]
[2, 1]
[3, 1]
[4, 1]
[3, 2]
[4, 2]
*/
Note that if you what to keep the subsets you can just insert them in some structure (such as a List
) instead of printing them.