全排列函数permutation

版权声明:转载请注明出处 https://blog.csdn.net/qq_41431457/article/details/88893562

这个函数有两个一个是next_permutation()另一个是prev_permutation()

假如我们有长度为3的排列,则全排列为:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

共六个

一、next_permutation()

这个函数是求此序列的下一个排列

假如我们另a[3] 等于第3个排列:2 1 3,则经过next_permutation(a,a+3),此时a里面存的第下一个排列:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[3]={2,1,3};
    next_permutation(a,a+3);	//生成下一个排列 
	cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;//输出 2 3 1 
    return 0;
}

二、prev_permutation()

这个函数是求此序列的上一个排列

同样a预先存储的是第三个排列:则经过prev_permutation(a,a+3)操作后,a存的是上一个排列:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[3]={2,1,3};//预先存第三个排列 
    prev_permutation(a,a+3);	//生成下一个排列 
	cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;//输出 1 3 2 
    return 0;
}

输出全排列:

尽量用do while循环,因为第一个排列也要输出:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int a[3]={1,2,3}; 
    do
    {
        cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
    }while(next_permutation(a,a+3));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41431457/article/details/88893562