题解 | #火车进站#
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
def dfs(wait, stack, out):
if not wait and not stack:
res.append(out)
if wait: # 入栈
dfs(wait[1:], stack + [wait[0]], out)
if stack: # 出栈
dfs(wait, stack[:-1], out + [stack[-1]])
#python 由于优秀的切片用法 这里DFS回溯遍历时 不用像c一样因为要用指针来标记栈顶而需要还原栈
#比如wait入栈 dfs后 c需要把指针从1处指回0处,stack也要还原
#但是python因为切片wait[1:] 所以指回就相当于用wait自动完成了
res = []
n = input()
wait = input().split()
dfs(wait, [], [])
res.sort()
for re in res:
print(" ".join(re))

查看12道真题和解析