题解 | #火车进站# 深度搜索优先 递归
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
# 后进先出
'''
1 2 3 | 3 2 1 一次停留3车
1 |2 3 2 3 1 第1次停留2车 第2次停留1车
|1 2 3 1 3 2 第1次停留1车 第2次停留2车
|1 |2 3 1 2 3 每次停留1车
1 2| 3 2 1 3 第1次停留2车 第2次停留1车
'''
# 来源:牛客网ID: 钻石王老五
#固定的递归方法,需要记住
res = [] #定义全局变量
def dfs(wait, stack, out):
if not wait and not stack:
# if listname 列表有值执行语句;if not listname 列表为空执行语句
res.append(' '.join(map(str, out)))
if wait: # 入栈,一开始一股脑都入栈
dfs(wait[1:], stack + [wait[0]], out)
if stack: # 出栈,之后慢慢出栈
dfs(wait, stack[:-1], out + [stack[-1]])
#return res
while True:
try:
n, nums = int(input()), list(map(int, input().split()))
dfs(nums, [], [])
for i in sorted(res):
print(i)
except:
break
查看9道真题和解析