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.
This is python. Sorry for the spanish ;)
Here is a Java version of what I think Simple is talking about, using a binary representation of all sets in the power set. It's similar to how Abhiroop Sarkar did it, but I think a boolean array makes more sense than a string when you are just representing binary values.
If you are looking for Iterator pattern answer then here you go.
Check out my solution
I am working on a 4 element set for test purpose and using k=2. What I try to do is initially generate a binary string where k bits are set and n-k bits are not set. Now using this string I find all the possible permutations of this string. And then using these permutations I output the respective element in the set. Would be great if someone could tell me about the complexity of this problem.
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: