题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
import java.util.*;
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static List<String> l = new ArrayList<>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] id = new int[n];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
id[i] = in.nextInt();
}
trainOut(id, 0, stack, "", 0);
//对结果集排序
Collections.sort(l);
for (String str : l) {
System.out.println(str);
}
}
public static void trainOut(int[] id, int i, Stack<Integer> s, String str, int n) {
if (n == id.length) {
l.add(str); //如果所有火车均出栈则将当前结果保存
}
if (!s.empty()) { //栈非空时出栈
int temp = s.pop();
trainOut(id, i, s, str + temp + " ", n + 1);
s.push(temp); //恢复现场
}
if (i < id.length) {
s.push(id[i]);
trainOut(id, i + 1, s, str, n);
s.pop(); //恢复现场
}
}
}
这道题没做出来,需要多了解栈的使用和DFS算法
注意:Stack是引用传参,所以每次push和pop都要还原,不然会影响到当前递归下面语句的执行
