开发者

Next_permutation and efficiency

Is it more efficient to begin with a possibly random ordering of objects in a range, using next_permutation to step through all greater permutations, followed by stepping down, beginning again with the original ordering, using prev_permutation to reach the last.

Or, to开发者_运维知识库 sort the range before permuting, then to use only next_permutation to step through all of them?


next_permutation will step through all permutations, not only through greater permutations. No need to revert and use prev_permutation, and certainly no need to sort.

You only need take care of the fact that next_permutation will return false once it “rolls over” into the lexicographically lowest permutation so you need to keep track of the number of the current permutation to know when to stop.

That is, the following will iterate through all possible permutations of a range, no matter how the starting range looks like.

size_t const num_permutations = multinomial_coefficient(range);

for (size_t i = 0; i < num_permutations; ++i) {
    next_permutation(range.begin(), range.end());
    // use permutation.
}

Where multinomial_coefficient is the multinomial coefficient of the number of distinct elements in the range. In the simple case where all elements are distinct, this is equivalent to N!, the factorial of the number of elements.


To get all permutations, start with a sorted range, then

do
{
  // something
} while(next_permutation(range.begin(), range.end());

It stops, when range is sorted again. The process is O(n!).

When you start with randomized range, you will miss some permutations.


There's no difference at all, the algorithm doesn't reuse previous results so there's no need to sort beforehand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜