 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
All ways of balancing n parenthesis in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should return an array showing all the ways of balancing n parenthesis.
For example, for n = 3, the output will be −
["()()()","(())()","()(())","(()())","((()))"]
Example
Following is the code −
const res = []; const buildcombination = (left, right, str) => {    if (left === 0 && right === 0) {       res.push(str);    }    if (left > 0) {       buildcombination(left-1, right+1, str+"(");    }    if (right > 0) {       buildcombination(left, right-1, str+")");    } } buildcombination(3, 0, ""); console.log(res); Output
Following is the console output −
[ '((()))', '(()())', '(())()', '()(())', '()()()' ]
Advertisements
 