समस्या
हमें एक JavaScript फ़ंक्शन लिखना है जो एक संख्या n लेता है। हमारा फ़ंक्शन n पैरेंथेसिस को बैलेंस करने के सभी तरीकों को दिखाने वाला एक ऐरे लौटाएगा। उदाहरण के लिए, n = 3 के लिए, आउटपुट होगा −
["()()()","(())()","()(())","(()())","((()))"]
उदाहरण
निम्नलिखित कोड है −
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);आउटपुट
कंसोल आउटपुट निम्नलिखित है −
[ '((()))', '(()())', '(())()', '()(())', '()()()' ]