题解 | #火车进站# dfs排列组合+验证是否合法简单易懂
火车进站
https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109
N = int(input()) ls = [str(i) for i in input().split()] def is_valid(ls,out): #验证是否合法 stack = [] index = 0 for num in ls: stack.append(num) while stack and stack[-1] == out[index]: stack.pop() index += 1 if not stack: return True else: return False res = [] path = [] vis = [False] * N def dfs(index): #排列组合 if len(path) == N: if is_valid(ls,path[:]): res.append(" ".join(path[:])) return for i in range(N): if not vis[i]: vis[i] = True path.append(ls[i]) dfs(i + 1) path.pop() vis[i] = False dfs(0) res = sorted(res) for i in res:print(i)