next_permutation 与 prev_permutation(全排列算法)

stl提供了权排列算法,以后暴力举例就方便多啦

文末有手动求,按字典序排序的全排列的第n个排列,的求法

next_permutation(a,a+4);  检测数组的a[0]到a[3],如果不是“完全倒序”(如:4,3,2,1),就继续执行全排列

prev_permulation(a,a+4);  与上面那个正相反

代码举例,next_permutation(a,a+4):

#include<iostream>  
#include<algorithm>  
using namespace std; 

bool cmp(const int &a,const int &b){
    return a>b;
} 
 
int main()  
{  
    int ans[4]={1,2,3,4};  
    sort(ans,ans+4);    /* 这个sort可以不用,因为{1,2,3,4}已经排好序*/  
                                 /*注意这步,如果是while循环,则需要提前输出*/  
    
        for(int i=0;i<4;++i)  
            cout<<ans[i]<<" ";  
        cout<<endl;  
    while(next_permutation(ans,ans+4))    {  
        for(int i=0;i<4;++i)  
            cout<<ans[i]<<" ";  
        cout<<endl;  
    };  
    return 0;  
} 

prev_permulation(a,a+4):

#include<iostream>  
#include<algorithm>  
using namespace std; 

bool cmp(const int &a,const int &b){
    return a>b;
} 
 
int main()  
{  
    int ans[4]={1,2,3,4};  
    sort(ans,ans+4,cmp);    /* 这个sort可以不用,因为{1,2,3,4}已经排好序*/  
                                 /*注意这步,如果是while循环,则需要提前输出*/  
    
        for(int i=0;i<4;++i)  
            cout<<ans[i]<<" ";  
        cout<<endl;  
    while(prev_permutation(ans,ans+4))    {  
        for(int i=0;i<4;++i)  
            cout<<ans[i]<<" ";  
        cout<<endl;  
    };  
    return 0;  
} 

以下内容转自:小与米

1.能否直接算出集合{1, 2, ..., m}的第n个排列?

举例说明:如7个数的集合为{1, 2, 3, 4, 5, 6, 7},要求出第n=1654个排列。

(1654 / 6!)取整得2,确定第1位为3(从0开始计数),剩下的6个数{1, 2, 4, 5, 6, 7},求第1654 % 6!=214个序列;

(214 / 5!)取整得1,确定第2位为2,剩下5个数{1, 4, 5, 6, 7},求第214 % 5!=94个序列;

(94 / 4!)取整得3,确定第3位为6,剩下4个数{1, 4, 5, 7},求第94 % 4!=22个序列;

(22 / 3!)取整得3,确定第4位为7,剩下3个数{1, 4, 5},求第22 % 3!=4个序列;

(4 / 2!)得2,确定第5为5,剩下2个数{1, 4};由于4 % 2!=0,故第6位和第7位为增序<1 4>;

因此所有排列为:3267514。

2. 给定一种排列,如何算出这是第几个排列呢?

和前一个问题的推导过程相反。例如3267514:

后6位的全排列为6!,3为{1, 2, 3 ,4 , 5, 6, 7}中第2个元素(从0开始计数),故2*720=1440;

后5位的全排列为5!,2为{1, 2, 4, 5, 6, 7}中第1个元素,故1*5!=120;

后4位的全排列为4!,6为{1, 4, 5, 6, 7}中第3个元素,故3*4!=72;

后3位的全排列为3!,7为{1, 4, 5, 7}中第3个元素,故3*3!=18;

后2位的全排列为2!,5为{1, 4, 5}中第2个元素,故2*2!=4;

最后2位为增序,因此计数0,求和得:1440+120+72+18+4=1654

柳暗花明又一村
原文地址:https://www.cnblogs.com/ucandoit/p/8550915.html