边工作边刷题: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
posted @ 2016-04-11 11:50  absolute100  阅读(91)  评论(0编辑  收藏  举报