输入一个数n,按照字典顺序从小到大打印出(1-n)的全排列。两个序列的字典序大小关系等价于从头开始第一个不相同位置处的大小关系。
Input
正整数n(1<=n<=7)。
Output
按照字典顺序从大到小打印全排列。每个样例之间有一个空格
Sample Input
1
2
3
4
Output
1
1
2
1 2
2 1
3
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
4
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
HINT
采取递归的方式枚举所有可能性,递归回到原点便将其还原。利用集合来存储所有可能的数,利用数组存储每一个全排列序列。利用递归特性实现从小到大字典顺序。
Accepted
#include<iostream>
#include<algorithm>
#include<cstring>
#include<set>
#include<vector>
using namespace std;
int num;
set<int>list;
set<int>temp;
vector<int>arr;
void Print(set<int>t) {
temp = t;
if (t.empty())
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << (i == arr.size() - 1 ? '\n' : ' ');
else for (auto i = t.begin(),j=temp.begin(); i != t.end(); i++) {
arr.push_back((*j));
temp.erase(j);
Print(temp);
temp = t;
j = temp.find((*i));
j++; arr.pop_back();
}
}
int main() {
while (cin >> num) {
list.clear();
for (int i = 1; i <= num; i++)
list.insert(i);
Print(list);
cout<<endl;
}
}