首页
学习
活动
专区
圈层
工具
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

数据结构算法操作试题(C++/Python)——括号生成

1. 题目

leetcode 链接:https://leetcode-cn.com/problems/generate-parentheses/submissions/

2. 解答

递归 python:32ms, 10MB, 92.65%

代码语言:javascript
复制
class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        resList = set()
        if n == 1: return ["()"]
        else:
            for i in self.generateParenthesis(n - 1):
                findParenthesisList = self.find_all(i, '()')
                for j in findParenthesisList:
                    tmpParenth = i[:j+1] + "()" + i[j+1:]
                    resList.add(tmpParenth)
                    tmpParenth = i[:j+2] + "()" + i[j+2:]
                    resList.add(tmpParenth)           
            return list(resList)
            
    def find_all(self, a_str, sub):
        start = 0
        while True:
            start = a_str.find(sub, start)
            if start == -1: return
            yield start
            start += len(sub)

其他方法看 leetcode 链接 评论区~

下一篇
举报
领券