next_permutation函数(全排列)

题目描述:有一个数n(1<n<10),写出1到n的全排列。

输入:第一行输入一个数n(0<n<10),表示有n组测试数据。后面的n行输入多组输入数据,每组输入数据都是一个整数x(0<x<10)

输出按特定顺序输出所有组合。
特定顺序:每一个组合中的值从小到大排列,组合之间按字典序排列。

输入:

2
2
3

输出:

12
21
123
132
213
231
312
321
#include<iostream>
#include<algorithm>
using namespace std;
int a[15];
int main()
{
    int n,x,i;
    cin>>n;
    ++n;
    while(--n)
    {
        cin>>x;
        for(i=0; i<x;++i)
            a[i]=i+1;
        for(i=0; i<x;++i)
            cout<<a[i];
        cout<<endl;
        while(next_permutation(a,a+x)==1)
        {
            for(i=0; i<x;i++)
                cout<<a[i];
            cout<<endl;
        }
    }
    return 0;
}

函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。

next_permutation(),可以遍历全排列,要包含头文件<algorithm>

与之完全相反的函数还有prev_permutation

基本格式:

int a[];
while(next_permutation(a,a+n))
{
}

 

posted on 2020-05-05 22:49  YovM_21  阅读(209)  评论(0编辑  收藏  举报

导航