Generate Parentheses in Python

PythonServer Side ProgrammingProgramming

Suppose we have a value n. We have to generate all possible well-formed parentheses where n number of opening and closing parentheses are present. So if the value of n = 3, then the parentheses set will be ["()()()","()(())","(())()","(()())","((()))"]

To solve this, we will follow these steps −

• Define method called genParenthesisRec(). This takes left, right, temp string and result array. initially result array is empty
• The function genParenthesisRec, will work like below
• if left = 0 and right := 0, then insert temp into result, and return
• if left > 0
• getParenthesisRec(left – 1, right, temp + “(”, result)
• if right > left
• getParenthesisRec(left, right – 1, temp + “)”, result)

Example(Python)

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
result = []
self.generateParenthesisUtil(n,n,"",result)
return result
def generateParenthesisUtil(self, left,right,temp,result):
if left == 0 and right == 0:
result.append(temp)
return
if left>0:
self.generateParenthesisUtil(left-1,right,temp+'(',result)
if right > left:
self.generateParenthesisUtil(left, right-1, temp + ')', result)
ob = Solution()
print(ob.generateParenthesis(4))

Input

4

Output

["(((())))",
"((()()))",
"((())())",
"((()))()",
"(()(()))",
"(()()())",
"(()())()",
"(())(())",
"(())()()",
"()((()))",
"()(()())",
"()(())()",
"()()(())",
"()()()()"]
Published on 30-Jan-2020 10:42:27