例如,给出n=3,解集为:
"((()))", "(()())", "(())()", "()()()", "()(())"
数据范围:
要求:空间复杂度 ,时间复杂度
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # @auther zhangjunyi # @time 20230309 # @param n int整型 # @return string字符串一维数组 # class Solution: def generateParenthesis(self , n: int) -> list[str]: # write code here #定义L1符号列表 L1 =["(",")"] #定义L2收集每个步骤的括号生成的结果,初始化为空 L2=[] #定义L3收集总共生成的结果,初始化为空 L3=[] L4=[] #定义变量i,j表示左右括号在L2中的数量,初始化为0 i=0 j=0 #定义回朔函数当j<i的时候,可以添加右括号,也可以添加左括号,用回朔法进行添加 def traversal(i,j,L1,L2): if j==i and i==n: L4.append(L2.copy()) return for x in L1: if x=="(" and i<n: L2.append(x) i+=1 traversal(i,j,L1,L2) i-=1 L2.pop() elif x==")" and j<i : L2.append(x) j+=1 traversal(i,j,L1,L2) j-=1 print(L2) print(L2[-1]) L2.pop() return L4 L4 = traversal(i,j,L1,L2) for x in L4: L3.append("".join(x)) return L3
class Solution: def generateParenthesis(self , num: int) -> List[str]: res = [] if num == 1: return ["()"] result = self.generateParenthesis(num - 1) for item in result: res.append("(" + item + ")") # 插到左边 res.append("()" + item) # 插到右边 res.append(item + "()") # 插到中间 for i in range(len(item)//2): res.append(item[:i] + "()" + item[i:]) return list(set(res))
class Solution: def recursion(self, left, right, temp, n, res): if left == n and right == n: res.append(temp) return if left < n: self.recursion(left + 1, right, temp + '(', n, res) if right < n and left > right: self.recursion(left, right + 1, temp + ')', n, res) def generateParenthesis(self , n: int) -> List[str]: res = [] temp = '' self.recursion(0, 0, temp, n, res) return res
class Solution: def generateParenthesis(self , n: int) -> List[str]: # write code here ''' 与全排列不同, 不需要首先生成再排序输出. ''' def dfs(res, cur: str): if len(cur) == n * 2 and cur.count(')') == cur.count('('): res.append(cur) if cur.count(')') > cur.count('('): return # 递归过程中右括号数一定小于左括号数. if cur.count('(') > n: return dfs(res, cur + '(') dfs(res, cur + ')') res = [] dfs(res, '') return res
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param n int整型 # @return string字符串一维数组 # class Solution: def generateParenthesis(self , n: int) -> List[str]: # write code here ret = [] tmp = [] def dfs(i, j): if i < j: return if i == n and j == n: ret.append(''.join(tmp)) if i <= n: tmp.append('(') dfs(i + 1, j) tmp.pop() if j <= n: tmp.append(')') dfs(i, j + 1) tmp.pop() dfs(0, 0) return ret
class Solution: def generateParenthesis(self , n: int) -> List[str]: # write code here res=[] def bfs(paths,left,right): if left>n&nbs***bsp;right>left: return if len(paths)==2*n: res.append(paths) return bfs(paths+'(',left+1,right) bfs(paths+')',left,right+1) bfs('',0,0) return res
class Solution: def generateParenthesis(self , n ): # write code here self.res = [] def dfs(l, r, tmp): if l==0 and r == 0: self.res.append(tmp) return if l > r: return if l> 0: dfs(l-1, r, tmp+'(') if r > 0: dfs(l, r-1, tmp+')') dfs(n, n, "") return self.res