LeetCode题库22.括号生成

 

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        if n==1:
            return ['()']
        if not n:
            return None
        stack,res,l,r=[],[],[],[]
        for _ in range(n):
            l.append('(')
            r.append(')')
        def dfs(l,r):
            if not l and not r:
                res.append(''.join(i for i in stack))
                return 
            if l:
                stack.append(l.pop())
                dfs(l,r)                
                l.append(stack.pop())            
            if r and len(l)!=len(r):
                stack.append(r.pop())
                dfs(l,r)
                r.append(stack.pop())
            print(r)
        dfs(l,r)
        return res

  

posted @ 2023-10-14 16:55  Aneverforget  阅读(2)  评论(0编辑  收藏  举报