Generating the complete power set of a collection involves binary decisions at each element. The recursive approach branches twice: once including the current element and once excluding it.
public void enumerateSubsets(int[] data, List<Integer> buffer, int idx) {
if (idx == data.length) {
System.out.println(buffer);
return;
}
buffer.add(data[idx]);
enumerateSubsets(data, buffer, idx + 1);
buffer.remove(buffer.size() - 1);
enumerateSubsets(data, buffer, idx + 1);
}
When selecting exactly k elements from n without regard to order, constrani the recursion to maintain a start index that prevents revisiting previous positions, ensuring unique combinations.
public void selectCombinations(int[] source, int k, int start, List<Integer> chosen) {
if (chosen.size() == k) {
System.out.println(chosen);
return;
}
for (int i = start; i < source.length; i++) {
chosen.add(source[i]);
selectCombinations(source, k, i + 1, chosen);
chosen.remove(chosen.size() - 1);
}
}
For partial permutations where order matters and we arrange r items from n distinct eelments, a boolean tracking array marks visited indices to prevent duplication in the current arrangement.
public void arrangePartial(int[] pool, int r, boolean[] used, List<Integer> sequence) {
if (sequence.size() == r) {
System.out.println(sequence);
return;
}
for (int i = 0; i < pool.length; i++) {
if (!used[i]) {
used[i] = true;
sequence.add(pool[i]);
arrangePartial(pool, r, used, sequence);
sequence.remove(sequence.size() - 1);
used[i] = false;
}
}
}
Full permutations of an array require generating all possible orderings. By swapping each elemennt into the current position and recursing on the remainder, we explore every arrangement efficiently without auxiliary storage for visited states.
public void generatePermutations(int[] sequence, int position) {
if (position == sequence.length) {
System.out.println(Arrays.toString(sequence));
return;
}
for (int i = position; i < sequence.length; i++) {
exchange(sequence, position, i);
generatePermutations(sequence, position + 1);
exchange(sequence, position, i);
}
}
private void exchange(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}