Bailian4047 全排列【全排列】

4070:全排列

描述

对于数组[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]的从小到大的全排列。

 

输入

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

输出

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

样例输入

2
3
0

样例输出

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

问题链接Bailian4047 全排列

问题分析

  这是一个全排列问题,用STL算法库中的函数next_permutation()来实现比较简单。需要注意的是,使用该函数之前,需要将原有的数据做个排序。

程序说明:(无)

题记:(略)

参考链接:(无)

AC的C++语言程序如下:

/* Bailian4047 全排列 */

#include <iostream>
#include <algorithm>
#include <stdio.h>

using namespace std;

const int N = 8;
int a[N];

int main()
{
    int n;
    while(~scanf("%d", &n) && n) {
        for(int i = 0; i < n; i++)
            a[i] = i + 1;
        sort(a, a + n);
        do {
            printf("%d", a[0]);
            for(int i = 1; i < n; i++)
                printf(" %d", a[i]);
            printf("\n");
        } while(next_permutation(a, a + n));
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/tigerisland45/article/details/82120448