Given a set {1,2,3,4,5...n} of n elements, we need to find all subsets of length k .
For example, if n = 4 and k = 2, the output would be {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}.
I am not even able to figure out how to start. We don’t have to use the inbuilt library functions like next_permutation etc.
Need the algorithm and implementation in either C/C++ or Java.
Recursion is your friend for this task.
For each element – “guess” if it is in the current subset, and recursively invoke with the guess and a smaller superset you can select from. Doing so for both the “yes” and “no” guesses – will result in all possible subsets.
Restraining yourself to a certain length can be easily done in a stop clause.
Java code:
Invoking with:
Will yield: