题目描述:
解题思路:
使用深度优先搜索的方法找到所有符合条件的答案。
这里引用大佬的解题思路图,原图链接
对于 n=2 的情况如下图所示。
从图中可以看出,深度优先遍历的函数包含的步骤为:
- 如果当前剩余的左右括号数都为0,则将当前的括号字符串添加进结果中
- 如果当前剩余的左括号数量大于右括号数量,那么得到的括号字符串不符合条件,需要进行剪枝
- 如果当前剩余的左括号数量大于0,则可进行左分支
- 如果当前剩余的右括号数量大于0,则可进行右分支
python代码
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
self.dfs("", n, n, result)
return result
def dfs(self, curStr, left, right, result):
"""
-curStr: 当前的括号字符串, type: str
-left: 当前左括号剩余数量, type: int
-right: 当前右括号剩余数量, type: int
-result: 存储的所有的结果, type: List[str]
"""
if left == 0 and right == 0:
result.append(curStr)
return
if left > right:
return
if left > 0:
self.dfs(curStr + "(", left - 1, right, result)
if right > 0:
self.dfs(curStr + ")", left, right - 1, result)
参考资料:
https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-suan-fa-by-liweiwei1419/