Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit fff5cb8

Browse files
Added Generate Parentheses
1 parent c497e7b commit fff5cb8

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

GenerateParentheses.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
https://leetcode.com/problems/generate-parentheses
3+
4+
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
5+
6+
For example, given n = 3, a solution set is:
7+
8+
[
9+
"((()))",
10+
"(()())",
11+
"(())()",
12+
"()(())",
13+
"()()()"
14+
]
15+
*/
16+
17+
var generateParentheses = function(n) {
18+
if(n == 0) { return [""] };
19+
20+
var str = "(".repeat(n);
21+
var sol = [];
22+
genParAux(str, 0, 0, sol)
23+
return sol;
24+
};
25+
26+
var genParAux = function(str, position, leftParentheses, sol) {
27+
if(position === str.length) {
28+
var ret = str + ")".repeat(leftParentheses);
29+
sol.push(ret);
30+
return;
31+
}
32+
33+
genParAux(str, position + 1, leftParentheses + 1, sol); // Don't insert anything
34+
if(leftParentheses == 0) { return; }
35+
36+
for(var i = 1; i <= leftParentheses; i++) {
37+
var parString = ")".repeat(i);
38+
var partSol = str.slice(0, position) + parString + str.slice(position); // Insert i parentheses in the position
39+
genParAux(partSol, position + i + 1, leftParentheses - i + 1, sol);
40+
}
41+
}
42+
43+
function main() {
44+
console.log("0:");
45+
console.log(generateParentheses(0));
46+
console.log("1:");
47+
console.log(generateParentheses(1));
48+
console.log("2:");
49+
console.log(generateParentheses(2));
50+
console.log("3:");
51+
console.log(generateParentheses(3));
52+
}
53+
54+
module.exports.main = main

Main.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22
var permutationWithoutDuplicates = require("./PermutationsWithoutDuplicates.js");
33
var permutationWithDuplicates = require("./PermutationsWithDuplicates.js");
44
var subsets = require("./Subsets.js");
5+
var generateParentheses = require("./GenerateParentheses.js")
56

67
// Invocation
78

89
// permutationWithoutDuplicates.main();
910
// permutationWithDuplicates.main();
10-
// subsets.main();
11+
// subsets.main();
12+
// generateParentheses.main();

0 commit comments

Comments
 (0)