From 565d94f8e08fd3837ad7222270b0a4df936213c7 Mon Sep 17 00:00:00 2001 From: Pranjal Goyal Date: Tue, 12 Oct 2021 22:33:41 +0530 Subject: [PATCH] Added GenerateParentheses solution (#539) * Added Soluion of ContainweWithMostWater problem * Added Example Signed-off-by: Pranjal Goyal * Added GenerateParentheses code * Updates Signed-off-by: Pranjal Goyal --- .../GenerateParentheses.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Programming/Python/GenerateParentheses/GenerateParentheses.py diff --git a/Programming/Python/GenerateParentheses/GenerateParentheses.py b/Programming/Python/GenerateParentheses/GenerateParentheses.py new file mode 100644 index 0000000..9196243 --- /dev/null +++ b/Programming/Python/GenerateParentheses/GenerateParentheses.py @@ -0,0 +1,30 @@ +""" +Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. + +Example - 1: +Input: n = 3 +Output: ["((()))","(()())","(())()","()(())","()()()"] +""" + +class Solution(object): + + # Storing the generated string + def generateParenthesis(self, n): + result = [] + self.generateRecurParen(n,n,"",result) + return result + + # Recursive call to left and right paren + def generateRecurParen(self, left,right,temp,result): + if left == 0 and right == 0: + result.append(temp) + return + if left>0: + self.generateRecurParen(left-1,right,temp+'(',result) + if right > left: + self.generateRecurParen(left, right-1, temp + ')', result) + +# Making object +object1 = Solution() +n = int(input("Enter the number of pairs: ")) +print(object1.generateParenthesis(n)) \ No newline at end of file