给定n对括号,要求输出所有合法的括号排列。
使用DFS算法,主要分为两种情况:
①若有剩余的“(”
,则添加“(”
后继续递归;
②若有剩余的“)”
,且“)”
的个数多于“(”
,即为排好的“(”
个数多于“)”
,这是判定是否合法的条件,则添加“)”
后继续递归。
class Solution(object):
def __init__(self):
self.res = []
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.helper("", n, n) #n个左括号,n个右括号
return self.res
def helper(self, path, left, right):
if left == 0 and right == 0:
self.res.append(path)
if left > 0:
self.helper(path+"(", left-1, right)
if right > 0 and right > left:
self.helper(path+")", left, right-1)