算法37--Generate Parentheses

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

产生配对的括号匹配序列

给定n,则最终输出的括号序列为2*n,假定最终序列是由括号依次放入,则假定左括号个数为opennum,右括号个数为closenum,当依次放入括号:

初始时,应该放入左括号   或者当opennum==closenum时,应该放入左括号

当opennum<n时,均可以放入左括号

当opennum>closenum时,说明此时左括号多于右括号,即此时应该放入右括号

当opennum<closenum时,此时已经不匹配,则停止放入

初始时,首先放入左括号,接着可以继续放入左括号,右括号放入的条件是左括号数目多于右括号,其余情况直接退出即可。

class Solution:
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        rr=[]
        s=''
        self.help(rr, 0, 0, s, n)
        return rr
       
    def help(self, rr, opennum, closenum, s, n):
        if len(s) == 2*n:
            rr.append(s)
            return
        if opennum < n:
            self.help(rr, opennum+1, closenum, s+'(', n)
        if closenum < opennum:
            self.help(rr, opennum, closenum+1, s+')', n)

判断一个括号序列是否是匹配的:

def defer(s='(()()()'):
    r=[]
    for c in s:
        if c=='(':
            r.append(c)
        else:
            if len(r)==0 or (len(r)>1 and r[-1]!='('):
                return False
            r.pop(-1)
    if len(r)==0:
        return True
    else:
        return False

猜你喜欢

转载自blog.csdn.net/u014106644/article/details/84323302