边工作边刷题:70天一遍leetcode: day 37

generate parentheses

思路:递归,def generateRec(n, diff, res, solutions): n: 待生成的左右括号组,diff:左右括号的个数差,遵循单向recursion的基本模式即可

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        def generateRec(n, diff, res, solutions):
            if diff==0 and n==0:
                solutions.append(''.join(res))
                return
            
            if diff<0:
                return
            
            if n>0:
                res.append('(')
                generateRec(n-1, diff+1, res, solutions)
                res.pop()
                
            res.append(')')
            generateRec(n, diff-1, res, solutions)
            res.pop()
        
        res = []
        solutions = []
        generateRec(n, 0, res, solutions)
        return solutions
原文地址:https://www.cnblogs.com/absolute/p/5678243.html