next_permutation函数(全排列)

next_permutation函数


    组合数学中经常用到排列,这里介绍一个计算序列全排列的函数:next_permutation(start,end),和prev_permutation(start,end)。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列pn,他的下一个序列pn+1满足:不存在另外的序列pm,使pn<pm<pn+1.


对于next_permutation函数,其函数原型为:

     #include <algorithm>

     bool next_permutation(iterator start,iterator end)

当当前序列不存在下一个排列时,函数返回false,否则返回true


我们来看下面这个例子:

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <algorithm>  
  3. using namespace std;  
  4. int main()  
  5. {  
  6.     int num[3]={1,2,3};  
  7.     do  
  8.     {  
  9.         cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;  
  10.     }while(next_permutation(num,num+3));  
  11.     return 0;  
  12. }  


输出结果为:


当我们把while(next_permutation(num,num+3))中的3改为2时,输出就变为了:


由此可以看出,next_permutation(num,num+n)函数是对数组num中的前n个元素进行全排列,同时并改变num数组的值。

另外,需要强调的是,next_permutation()在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:



此外,next_permutation(node,node+n,cmp)可以对结构体num按照自定义的排序方式cmp进行排序。


猜你喜欢

转载自blog.csdn.net/summerone123/article/details/79324908