leetcode 链接:https://leetcode-cn.com/problems/generate-parentheses/submissions/
递归 python:32ms, 10MB, 92.65%
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 链接 评论区~