1620: 全排列
Time Limit: 1 Sec Memory Limit: 128 MB
[Submit][Status][Web Board]
Description
给定n个数 a[0] , a[1] … a[n-1], 输出其全排列。
Input
第一行输入一个数n,(n<7)
接下来一行输入n个数。
Output
按字典序从小到大输出全排列
Sample Input
3
1 2 3
3
1 2 2
Sample Output
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
1 2 2
2 1 2
2 2 1
AC代码:
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int n;
while(~scanf("%d",&n))
{
int a[n];
for(int i = 0; i < n; i++)
scanf("%d",&a[i]);
sort(a,a+n);
do
{
int i = 0;
printf("%d",a[i]);
for(i = 1; i < n; i++)
printf(" %d",a[i]);
printf("\n");
}while(next_permutation(a,a+n));
}
return 0;
}
总结:
next_permutation为C++库中全排列函数
使用:
- 使用前加头文件:
#include <algorithm>
和using namespace std;
- 要按字典序输出,则在全排之前对数据处理,可以直接用sort处理。
- next_permutation会自动去重。