-
Notifications
You must be signed in to change notification settings - Fork 91
/
Generate_Parenthesis.js
97 lines (79 loc) · 2.2 KB
/
Generate_Parenthesis.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Generate Parentheses
https://leetcode.com/problems/generate-parentheses
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
// ************************************************ Approach1 ************************************************
var generateParenthesisApproach1 = function (n) {
if (n === 0) return [];
var str = "(".repeat(n);
var sol = [];
genParAux(str, 0, 0, sol);
return sol;
};
var genParAux = function (str, position, leftParentheses, sol) {
if (position === str.length) {
var ret = str + ")".repeat(leftParentheses);
sol.push(ret);
return;
}
genParAux(str, position + 1, leftParentheses + 1, sol); // Don't insert anything
if (leftParentheses === 0) return;
for (var i = 1; i <= leftParentheses; i++) {
var parString = ")".repeat(i);
var partSol = str.slice(0, position) + parString + str.slice(position); // Insert i parentheses in the position
genParAux(partSol, position + i + 1, leftParentheses - i + 1, sol);
}
};
// ************************************************ Approach2 ************************************************
var generateParenthesisApproach2 = function (n) {
if (n === 0) return [];
var sol = [];
genParAuxApproach2("", 0, 0, 0, n * 2, sol);
return sol;
};
var genParAuxApproach2 = function (
str,
leftPar,
rightPar,
index,
totalCharCount,
sol
) {
if (index === totalCharCount) {
if (rightPar === leftPar) sol.push(str);
return;
}
var strLeft = insertAt(str, index, "(");
genParAuxApproach2(
strLeft,
leftPar + 1,
rightPar,
index + 1,
totalCharCount,
sol
);
if (rightPar === leftPar) return;
var strRight = insertAt(str, index, ")");
genParAuxApproach2(
strRight,
leftPar,
rightPar + 1,
index + 1,
totalCharCount,
sol
);
};
var insertAt = function (str, position, value) {
return str.slice(0, position) + value + str.slice(position);
};
module.exports.generateParenthesisApproach1 = generateParenthesisApproach1;
module.exports.generateParenthesisApproach2 = generateParenthesisApproach2;