topic:
22, parenthesis generation
The number n represents the logarithm of generating brackets. Please design a function to generate all possible and effective bracket combinations.
Example 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
prompt:
1 <= n <= 8
Problem solution ideas:
Set the template of the backtracking method directly, and then define a function that judges the validity of the brackets.
Backtracking python template: https://blog.csdn.net/weixin_44414948/article/details/114489545
Problem solution python code:
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if not n:
return list()
T = ["(", ")"]
res = []
path = []
def valid(s: str):
count = 0
for a in s:
if count<0: return False
if a=="(": count+=1
else: count -= 1
return count==0
def backtrack(index: int):
if index==2*n:
t = "".join(path)
if valid(t):
res.append(t)
return
for ch in T:
path.append(ch)
backtrack(index+1)
path.pop()
backtrack(0)
return res
Author: a-qing-ge
links: https://leetcode-cn.com/problems/generate-parentheses/solution/hui-su-mo-ban-ti-by-a-qing-ge-njqe/
Source: force LeetCode (LeetCode) https://leetcode-cn.com/problems/generate-parentheses/