forked from rubythonode/javascript-problems-and-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-parentheses.js
More file actions
42 lines (37 loc) · 806 Bytes
/
generate-parentheses.js
File metadata and controls
42 lines (37 loc) · 806 Bytes
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
/**
* 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:
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*/
/**
* @param {number} n
* @return {string[]}
*/
const generateParenthesis = n => {
const results = [];
backtracking(n, 0, 0, '', results);
return results;
};
const backtracking = (n, left, right, solution, results) => {
if (left === n && right === n) {
results.push(solution);
return;
}
if (left < n) {
backtracking(n, left + 1, right, solution + '(', results);
}
if (right < left) {
backtracking(n, left, right + 1, solution + ')', results);
}
};
export default generateParenthesis;