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.
JavaScript implementation:
This is an implemation in F#:
You can try it in the F# REPL:
This Java class implements the same algorithm:
If you do not like F# or Java then visit this website. It lists solutions to your particular problem in various programming languages:
http://rosettacode.org/wiki/Combinations
Here is an iterative version in python. Essence of it is increment_counters() function which returns all possible combinations. We know it needs to be called C(n,r) times.
Use a bit vector representation of the set, and use an algorithm similar to what std::next_permutation does on 0000.1111 (n-k zeroes, k ones). Each permutation corresponds to a subset of size k.
Please check my solution:-
This is similar to String permutations:-