给定一个正整数N代表火车数量,0《N《10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号。要求以字典序排序输出火车出站的序列号。
输入描述:
有多组测试用例,每一组第一行输入一个正整数N(0《N《10),第二行包括N个正整数,范围为1到9。
输出描述:
输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。
示例1
输入
3
1 2 3
输出
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
public class Main{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
//出栈全排序问题,可用递归
//利用两个栈来模拟出栈入栈
while(sc.hasNext()) {
int n = sc.nextInt();
int a[] = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Stack<Integer> stk1 = new Stack<>();
Stack<Integer> stk2 = new Stack<>();
for(int i = n - 1; i >= 0; i--) {
stk1.push(a[i]);
}
List<String> res = new ArrayList<>();
process("", stk1, stk2, res);
Collections.sort(res);
for(String s : res) {
System.out.println(s);
}
}
sc.close();
}
private static void process(String str, Stack<Integer>stk1, Stack<Integer>stk2, List<String> res) {
if(stk1.isEmpty() && stk2.isEmpty()) {
res.add(str.trim()) ;//过滤首位空白
return;
}
//stk1本身是倒序,进入stk2的就成了正常顺序
//stk1模拟进栈
if(!stk1.isEmpty()) {
stk2.push(stk1.pop());
process(str, stk1, stk2, res);
stk1.push(stk2.pop());
}
//stk2模拟出栈
if(!stk2.isEmpty()) {
int tmp = stk2.pop();
process(str+" "+tmp, stk1, stk2, res);
stk2.push(tmp);
}
}
}