版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shiliang97/article/details/96484775
请编写程序输出前n个正整数的全排列(n<10),并通过9个测试用例(即n从1到9)观察n逐步增大时程序的运行时间。
输入给出正整数n(<10)。
输出1到n的全排列。每种排列占一行,数字间无空格。排列的输出顺序为字典序,即序列a1,a2,⋯,an排在序列b1,b2,⋯,bn之前,如果存在k使得a1=b1,⋯,ak=bk 并且 ak+1<bk+1。
3
123
132
213
231
312
321
#include<iostream>
#include <algorithm>
using namespace std;
int main(){
int n;
cin>>n;
string str="";
for(int i=1;i<=n;i++){
str+=i+'0';
}
do{
cout<<str<<endl;
}while(next_permutation(str.begin(),str.end()));
return 0;
}
#include <bits/stdc++.h>
using namespace std;
string s;
int n;
set<string> sls;
void qpl(string s,int x)
{
if(x==s.length()){
sls.insert(s);
return;
}
for(int i = x; i<s.length(); ++i)
{
string t(s);
swap(t[x],t[i]);
qpl(t,x+1);
}
}
int main()
{
int n;
cin >> n;
for(int i=1; i<=n; ++i)
{
s+= i+'0';
}
for(int i = 0; i<s.length(); ++i)
{
string t(s);
swap(t[0],t[i]);
qpl(t,1);
}
for(auto st:sls){
cout<<st<<endl;
}
return 0;
}