【OpenJ_Bailian - 4070 】全排列

全排列


Descriptions:

对于数组[1, 2, 3],他们按照从小到大的全排列是

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

现在给你一个正整数n,n小于8,输出数组[1, 2, …,n]的从小到大的全排列。

 

Input

输入有多行,每行一个整数。当输入0时结束输入。

Output

对于每组输入,输出该组的全排列。每一行是一种可能的排列,共n个整数,每个整数用一个空格隔开,每行末尾没有空格。

Sample Input

2

3

0

Sample Output

1 2

2 1

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

题目链接:

https://vjudge.net/problem/OpenJ_Bailian-4070

 

讲一个STL函数:

int 类型的next_permutation
 
int main()
{
    int a[3];
    a[0]=1;
    a[1]=2;
    a[2]=3;
    do
    {
        cout<<a[0]<<""<<a[1]<<""<<a[2]<<endl;
    }
    while (next_permutation(a,a+3));   //参数3指的是要进行排列的长度

//如果存在a之后的排列,就返回true。如果a是最后一个排列没有后继,返回false,每执行一次,a就变成它的后继

}

 


 
输出:
 
 1 2 3
 1 3 2
 2 1 3
 2 3 1
 3 1 2
 3 2 1
 

如果改成 while(next_permutation(a,a+2));
则输出:
 1 2 3
 2 1 3
 
只对前两个元素进行字典排序
显然,如果改成 while(next_permutation(a,a+1)); 则只输出:1 2 3

 
若排列本来就是最大的了没有后继,则next_permutation执行后,会对排列进行字典升序排序,相当于循环
 
 int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<""<<list[1]<<""<<list[2]<<endl;
 
//输出: 1 2 3 
 
AC代码
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <numeric>
using namespace std;
typedef long long ll;
int n;
int main()
{
    while(cin >> n && n!=0)
    {
        int a[15];
        for(int i=0; i<n; i++)
            a[i]=i+1;
        int j;
        do
        {
            for(int i=0; i<n; i++)
            {
//                输出格式,特殊处理
                if(i==n-1)
                    cout<<a[i];
                else
                    cout <<a[i]<< " ";
            }
            cout << endl;
        }
        while(next_permutation(a,a+n));
    }
}

 

posted on 2019-05-30 11:01  Sky丨Star  阅读(836)  评论(0编辑  收藏  举报

导航