排列题应试技巧

想要求一个序列的全排列,有几种方法,一种是可以查看数论中的排列方法,递归式的。
另一种可以使用下面的取巧式的应试方法。

都知道

#include <algorithm>

其中,上面的头文件中有

//判断一个序列是否是另一个序列的一种排序
is_permutation()


//返回给定范围中的元素组成的下一个按字典序的排列
next_permutation()


//返回给定范围中的元素组成的上一个按字典序的排列
prev_permutation()

用next_permutation和prev_permutation求排列组合很方便,但是要记得包含头文件

#include <algorithm>

虽然最后一个排列没有下一个排列,用next_permutation会返回false,但是使用了这个方法后,序列会变成字典序列的第一个,如cba变成abc。prev_permutation同理。

这里,先演示一段运用next_permutation()函数
求出全排列的代码

举例输出123的全排列

输出

123
132
213
231
312
321 
#include <cstdio>
#include <algorithm>


using namespace std;

int main()
{
    int a[5]={
  1,2,3};

    //a[0]~a[2]之间的序列需要求解next_permutation() 

    do{

        printf("%d%d%d\n",a[0],a[1],a[2]);

    }while( next_permutation(a,a+3) );




    return 0;
} 



那么is_permutation()如何用呢?

返回值是bool
参数依次是  first1,last1,first2

下面举例:

输出

1
#include <cstdio>
#include <iostream>
#include <algorithm>


using namespace std;

int main()
{
    int a[5]={
  1,2,3};

    int b[6]={
  1,2,3};


    bool res;

    res=is_permutation(a,a+3,b);

    cout<<res<<endl;




    return 0;
} 




输出

0
#include <cstdio>
#include <iostream>
#include <algorithm>


using namespace std;

int main()
{
    int a[5]={
  1,2,3};

    int b[6]={
  1,2,4};


    bool res;

    res=is_permutation(a,a+3,b);

    cout<<res<<endl;




    return 0;
}