【STL】next_permutation

C++的STL有一個函數可以方便地生成全排列,這就是next_permutation,next_permutation函數的返回值類型是bool型。

#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    int n,p[10];
    cin>>n;
    for(int i(0);i<n;i++)
        cin>>p[i];
    sort(p,p+n);
    do
    {
        for(int i(0);i<n;i++)
            cout<<p[i]<<" ";
        cout<<endl;
    }while(next_permutation(p,p+n));<span style="white-space:pre">	</span>//如果在字典序中比該序列大的下一個序列存在則返回真
	return 0;
}
輸入:

3

3 2 1

輸出:

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1


該函數同時還可以對字符串進行字典序全排序,與該函數相反的函數是prev_permutation。

#include<iostream>
#include<algorithm>
using namespace std;
int compare(int a,int b)
{
    return a>b;
}
int main()
{
    int n,p[10];
    cin>>n;
    for(int i(0);i<n;i++)
        cin>>p[i];
    sort(p,p+n,compare);
    do
    {
        for(int i(0);i<n;i++)
            cout<<p[i]<<" ";
        cout<<endl;
    }while(prev_permutation(p,p+n));
	return 0;
}
輸入:

3

1 2 3

輸出:

3 2 1

3 1 2

2 3 1

2 1 3

1 3 2

1 2 3


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章