- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Generate Parentheses in Python
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 −
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
["(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()"]
Advertisements