Generate Parentheses

此题在回溯里面有一定特殊性,例如合法括号序列本身的一些逻辑,这里主要注意两点,合法的可以往前继续搜索的序列左括号数必定大于等于右括号数且左括号数的和不能大于n,根据这两个条件可以推得当前序列加左括号或右括号的逻辑,下面是代码

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        tmp, res = [], []
        self.helper(0, 2 * n, 0, 0, tmp, res)
        return res

    def helper(self, start, end, left, right, tmp, res):
        if start == end and left == right:
            ref = tmp[:]
            res.append(''.join(ref))
            return 

        if left < end / 2:
            tmp.append('(')
            self.helper(start + 1, end, left + 1, right, tmp, res)
            tmp.pop()

        if left > right:
            tmp.append(')')
            self.helper(start + 1, end, left, right + 1, tmp, res)
            tmp.pop()

results matching ""

    No results matching ""