题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
def fun(in_list,stack,out_list):
# in_list表示未进站的火车,从前往后进
# stack表示在站中的火车,从后往前出
# out_list表示已经出站的火车,直接添加在列表后
if not in_list and not stack: # 两个列表都为空,没有未进站的火车,站中也没有火车,说明全部出站
res.append(out_list) # 添加一种可能的出站序列
if in_list: # stack为空,站中没有火车
# 只能进站
fun(in_list[1:],stack+[in_list[0]],out_list)
# in_list[1]表示从下标为1的元素开始到最后
# 把第一个元素in_list[0]添加到stack中
if stack: # in_list为空,没有待进站的火车
# 只能出站
fun(in_list,stack[:-1],out_list+[stack[-1]])
# stack[:-1]表示去掉最后一个元素的列表
# 把最后一个元素添加到out_list
return res
# 获取火车数量
n=int(input())
# 获取火车入栈顺序
li=list(map(int,input().split(" ")))
# 输出出站的可能序列
res=[] # 存储所有的出站序列
fun(li,[],[])
for i in sorted(res): # 根据res中的列表首元素排序
print(" ".join(map(str,i))) # 将res中的每个列表元素转为字符串,再将每个字符用空格分隔
写了详细的注释,应该能看懂。

