题目描述
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ “((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”]
算法思路
递归
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return [""]
elif n == 1:
return ["()"]
elif n == 2:
return ["()()", "(())"]
result = []
for i in range(n):
j = n - 1 - i
temp1 = self.generateParenthesis(i)
temp2 = self.generateParenthesis(j)
result.extend(["(%s)%s" % (p, q) for p in temp1 for q in temp2])
return result
深度优先搜索+剪枝
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n==0:return ['']
if n==1:return ['()']
self.res=[]
self.helper(n,n)
return self.res
def helper(self,l,r,tp=''):
'''
l:左括号数
r:右括号数
tp:临时保存当前括号组合
'''
# 当左括号数量多于右括号时,表示当前tp不是合法括号,回溯。
if l>r:return
if l==0 and r==0:
self.res.append(tp)
return
if l:self.helper(l-1,r,tp+'(')
if r:self.helper(l,r-1,tp+')')
执行用时 :44 ms, 在所有 Python3 提交中击败了48.48%的用户
内存消耗 :13.8 MB, 在所有 Python3 提交中击败了5.03%的用户
其他参考
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
result = "()"*n
p = Solution.permutation
result = p(self, result)
r = []
for i in result:
if Solution.validParentheses(self, i):
r.append(i)
return r
def validParentheses(self, s:str):
if not s:
return True
left_p = []
dict_p = {")": "("}
for i in s:
if i == "(":
left_p.append(i)
if i == ")":
if not left_p:
return False
if dict_p[i] == left_p[-1]:
left_p.pop()
else:
return False
return left_p == []
def permutation(self, s: str): # 超时,可能是因为全排列重复的太多了.手动写个全排列就稳了.
if len(s) == 1:
return s
count = 1
result = [s[0]]
while count < len(s):
temp = []
for i in result:
for j in range(len(result[0]) + 1):
temp.append(i[:j] + s[count] + i[j:])
temp = list(set(temp))
result = temp[:]
count += 1
return result
执行用时 :152 ms, 在所有 Python3 提交中击败了5.30%的用户
内存消耗 :26 MB, 在所有 Python3 提交中击败了5.19%的用户
————————
2020/04/21 面试题08.09:括号 打卡
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
l=r=n
res=[]
def helper(l,r,s=''):
if l>r:return
if not l and not r:res.append(s)
if l:helper(l-1,r,s+'(')
if r:helper(l,r-1,s+')')
helper(l,r)
return res
执行用时 :36 ms, 在所有 Python3 提交中击败了92.63%的用户
内存消耗 :13.8 MB, 在所有 Python3 提交中击败了100.00%的用户