lundi 23 mai 2016

Implementing a next_combination() function in C++ using std::next_permutation

I want to implement an efficient non-recursive algorithm to generate combinations of size K from a set of size N in C++. So, basically if I have the following set of numbers [1, 2, 3, 4] then N = 4 and K = 2. This would give us the following set of numbers in the combination {1, 2}, {1, 3}, {1, 4}, {2, 1}, {2, 2} ... etc.

I don't want to generate the same set twice, so {1, 2} and {2, 1} are the same set.

My idea was to use the std::next_permutation from C++ and then if I look at just the first K elements of each permutation, then I have all possible combinations of size K from a set of size N.

Now this is highly inefficient because I generate N! permutations where most of the sets repeat : {1, 2} appears more than once because of the way permutations are generated.

Is there a very efficient way in C++ to generate these numbers from a set iteratively. I don't need to store the numbers anywhere I will only be looking at one combination at a time.

Aucun commentaire:

Enregistrer un commentaire