蓝桥杯需要掌握的知识点3(全排列函数next_permutation)

一,对数字排列

#include <iostream>  

#include <algorithm>  

using namespace std;  

int main()  

 {  

    int num[3]={1,2,3};  

    do  
  {  

    cout<<num[0]<<""<<num[1]<<""<<num[2]<<endl;} while(next_permutation(num,num+3));     
    return 0;  
 }

运行结果为:

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

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

1 2 3

2 1 3

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

2 3 1

3 1 2

3 2 1

二,对字母全排列

int main()

{

    string str = "abcde";

    int num = 1;

    while(next_permutation(str.begin(),str.end()))

    {

        num++;

        cout<<str<<endl;

        if(num==5)

            break;

    }

    return 0;

}

结果:

a b c e d

a b d c e

a b d e c

a b e c d

猜你喜欢

转载自blog.csdn.net/qq_58136559/article/details/129868304
今日推荐