描述
给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,一共N辆火车,每辆火车以数字1-9编号,火车站只有一个方向进出,同时停靠在火车站的列车中,只有后进站的出站了,先进站的才能出站。
要求输出所有火车出站的方案,以字典序排序输出。
数据范围: 1≤n≤10
进阶:时间复杂度:O(n!) ,空间复杂度:O(n)
输入描述:
第一行输入一个正整数N(0 < N <= 10),第二行包括N个正整数,范围为1到10。
输出描述:
输出以字典序从小到大排序的火车出站序列号,每个编号以空格隔开,每个输出序列换行,具体见sample。
示例1
输入:
3 1 2 3输出:
1 2 3 1 3 2 2 1 3 2 3 1 3 2 1说明:
第一种方案:1进、1出、2进、2出、3进、3出 第二种方案:1进、1出、2进、3进、3出、2出 第三种方案:1进、2进、2出、1出、3进、3出 第四种方案:1进、2进、2出、3进、3出、1出 第五种方案:1进、2进、3进、3出、2出、1出 请注意,[3,1,2]这个序列是不可能实现的。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
int[] array = new int[a];
for (int i=0; i<a; i++) {
array[i]=in.nextInt();
}
Stack<Integer> stack = new Stack<Integer>();
Set<String> set = new TreeSet<>();
getRes(array, a, 0, stack, set, "");
for (String tmp : set) {
System.out.println(tmp);
}
}
}
public static void getRes(int[] array, int size, int index, Stack<Integer> stack, Set<String> set, String order) {
if (index >= size) {
while (!stack.isEmpty()) {
order = order+stack.pop()+" ";
}
set.add(order);
return ;
}
if (!stack.isEmpty()) {
Stack<Integer> stackW = copy(stack);
stack.add(array[index]);
int tmpIndex = 1;
String tmpOrder = order;
getRes(array, size, index+1, stack, set, order);
while (!stackW.isEmpty()) {
tmpIndex++;
tmpOrder = tmpOrder+stackW.pop()+" ";
Stack<Integer> stackVal = copy(stackW);
stackVal.add(array[index]);
getRes(array, size, index+1, stackVal, set, tmpOrder);
}
}
else {
stack.add(array[index]);
getRes(array, size, index+1, stack, set, order);
}
}
public static Stack<Integer> copy(Stack<Integer> stack) {
Stack<Integer> res = new Stack<Integer>();
Object[] objs = stack.toArray();
for(Object tmp : objs) {
res.add((int)tmp);
}
return res;
}
}