leetcode-Generate Parentheses

2,862次阅读
没有评论

共计 588 个字符,预计需要花费 2 分钟才能阅读完成。

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
 解题思路
 从左到右生成相应的符号序列,首先添加‘(’,左右括号成对出现且个数一致,右边括号计数大于左边括号时需要添加‘)’,直到计数都为0时表示当前生成一个有效的序列,依次递归操作
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        def gernerate_str(sstr,lnum,rnum,result=[]):
            if lnum==0 and rnum==0:
                result.append(sstr)
                return
            if lnum>0:
                gernerate_str(sstr+'(',lnum-1,rnum,result)
            if rnum>lnum:
                gernerate_str(sstr+')',lnum,rnum-1,result)
        result=[]
        gernerate_str('',n,n,result)
        return result
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2017-04-16发表,共计588字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码