例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()()()", "()(())"
数据范围:
要求:空间复杂度
,时间复杂度 )
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param n int整型
# @return string字符串一维数组
#
class Solution:
def generateParenthesis(self , n: int) -> List[str]:
# write code here
res = []
l,r = n,n
if n == 1:
return ["()"]
def bracket(l,r,tmp):
if r < l:#越界条件,不能先输出),剩余r的数量一定大于l
return
if l == 0 and r == 0:#每轮终止条件,剩余lr都为0,则加入到res里
res.append(tmp)
if l > 0:
bracket(l-1,r,tmp + "(")
if r > 0:
bracket(l,r-1,tmp + ")")
bracket(l,r,'')
return res
class Solution:
def recursion(self, string, res, length):
tmp = "".join(string)
if len(string) == length:
res.add(tmp)
return res
for i in range(len(string)):
string.insert(i, ')')
string.insert(i, '(')
self.recursion(string, res, length)
string.pop(i)
string.pop(i)
def generateParenthesis(self , n):
# write code here
length = 2*n
string = ['(',')']
res = set()
self.recursion(string, res, length)
res = list(res)
return res class Solution:
def generateParenthesis(self , n: int) -> List[str]:
# write code here
ans = []
def dfs(left, right, path):
if left == right == 0:
ans.append(path)
return
if left > 0:
dfs(left - 1, right, path + "(")
if left < right:
dfs(left, right - 1, path + ")")
dfs(n, n, "")
return ans class Solution:
def generateParenthesis(self , n: int) -> List[str]:
# write code here
def dfs(l, r, s):
if l == n and r == n:
total.append(s)
return
if l <= n:
dfs(l + 1, r, s + '(')
if r <= n and l > r:
dfs(l, r + 1, s + ')')
total = []
dfs(0, 0, '')
return total 思路简单易懂,自行食用