[LeetCode][python3]0022. Generate Parentheses

class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n==0:
return []
ans=[]
cur_str=""
self.adder(ans,n,n,cur_str)
return ans


def adder(self,ans,l,r,cur_str):
if r==0:
ans.append(cur_str)
return
if l==r:
self.adder(ans,l-1,r,cur_str+"(")
else:
self.adder(ans,l,r-1,cur_str+")")
if l>0:
self.adder(ans,l-1,r,cur_str+"(")
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = ["()"]
for i in range(n - 1):
res = set([x[:i] + "()" + x[i:] for x in res for i in range(len(x))])
return res

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ruka

Ruka

HI I’m Ruka. Now a SWE in Taiwan. Contact via email: nayzi9999@gmail.com