题解 | #火车进站# 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)

全部评论

相关推荐

04-09 09:47
门头沟学院 Java
Arbelite_:2-3k,这工资还不如去摇奶茶
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客企业服务