简体   繁体   English

Next_permutation 和效率

[英]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.从一个范围内的对象的可能随机排序开始是否更有效,使用 next_permutation 逐步遍历所有更大的排列,然后降级,再次从原始排序开始,使用 prev_permutation 到达最后一个。

Or, to sort the range before permuting, then to use only next_permutation to step through all of them?或者,在排列之前对范围进行排序,然后只使用 next_permutation 来遍历所有这些?

next_permutation will step through all permutations, not only through greater permutations. next_permutation将逐步遍历所有排列,而不仅仅是通过更大的排列。 No need to revert and use prev_permutation , and certainly no need to sort.无需还原和使用prev_permutation ,当然也无需排序。

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.您只需要注意这样一个事实,即next_permutation一旦“翻转”到字典顺序最低的排列中就会返回false ,因此您需要跟踪当前排列的数量以知道何时停止。

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.其中multinomial_coefficient是范围内不同元素数量的多项式系数 In the simple case where all elements are distinct, this is equivalent to N ,.在所有元素都不同的简单情况下,这等价于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.).这个过程是 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.完全没有区别,该算法不会重复使用以前的结果,因此无需事先排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM