-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparentheses.js
More file actions
57 lines (43 loc) · 765 Bytes
/
parentheses.js
File metadata and controls
57 lines (43 loc) · 765 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Generate Parentheses
/*
n = 1 => 1 ()
n = 2 => 2 ()(),
n = 3 => 5
n =
1 2 3 4
(), (()), ((())), (((())))
()(), (()()), (()()())
(())(), ((()))()
()(()), ()((()))
()()(), ()()()()
((()()))
(())(())
n = 4
if(x === 0) then (
if(x === n) then )
*/
function getParentheses(n) {
var res = [];
function bt(res, parens, open, closed, n){
if(parens.length === n*2){
res.push(parens);
return;
}
if(open < n) {
bt(res, parens + '(', open+1, closed, n);
}
if(closed < open) {
bt(res, parens + ')', open, closed+1, n);
}
}
bt(res, '', 0, 0, n);
return res;
}
/*
res: []
parens: (())
open: 2
closed: 0
n: 3
*/
console.log(getParentheses(4));