【leetcode刷题】22. Generate Parentheses

原题链接:https://leetcode.com/problems/generate-parentheses/
解题思路:括号的生成大概遵循以下法则:
1、当字符串为空时,只能加入左括号
2、当之前的括号全都成对时(即左右括号数量相等),下一个只能出现左括号
3、当之前左括号数量多于右括号时,下一个可以是左括号或右括号。
代码:

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """

        string = ''
        result = []
        while n > 0:
            string = self.addString(string)
            n -= 0.5
        for item in string:
            if item.count('(')==item.count(')'):
                result.append(item)
        return result

    def addString(self, string):
        result = []
        if string == '':
            result.append('(')
            return result
        else:
            for item in string:
                if item.count('(') > item.count(')'):
                    result.append(item + '(')
                    result.append(item + ')')
                elif item.count('(') == item.count(')'):
                    result.append(item + '(')
            return result

猜你喜欢

转载自blog.csdn.net/weixin_39746008/article/details/88833717
今日推荐