[leetcode] 22. Generate Parentheses @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/86599763

原题

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

解法

DFS. 先定义左括号和右括号的数量, 然后进行深度优先搜索, 由于需要产生合法的括号, 那么左括号肯定先用完, 剩余的右括号>= 剩余的左括号. edge case是当剩余的右括号<左括号时, 直接返回. 如果不加edge case, 则会出现类似"(()))("的非法括号. 递归终止条件是当左右括号都用完时, 将path加到结果中.

代码

class Solution:
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """    
        res = []
        left, right = n, n
        if n == 0:
            return res
        self.dfs(left, right, '', res)
        return res       
        
        
    def dfs(self, left, right, path, res): 
        # edge case: right must >= left
        if right < left:
            return
        if not left and not right:
            res.append(path)
        if left:
            self.dfs(left-1, right, path+'(', res)
        if right:
            self.dfs(left, right-1, path+')', res)
            

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/86599763