-
Notifications
You must be signed in to change notification settings - Fork 8
/
generate-parentheses.js
99 lines (93 loc) · 2.22 KB
/
generate-parentheses.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
98
//
// 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 {string[]} result
* @param {string} currentStr
* @param {number} left the count of '{'
* @param {number} index from 1
* @param {number} n
*/
var procedure = function(result,currentStr,left,index,n) {
if (left >= n / 2) {
for (var i = index;i <= n;++i) {
currentStr += ')';
}
currentStr && result.push(currentStr);
return;
}
procedure(result,currentStr+'(',left+1,index+1,n);
if (index <= left * 2) {
procedure(result,currentStr+')',left,index+1,n);
}
};
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
var result = [];
procedure(result,'',0,1,n*2);
return result;
};
var procedure = function(result,currentStr,left,index,n) {
if (index > n) {
currentStr && result.push(currentStr);
return;
}
if (left >= n / 2) {
for (var i = index;i <= n;++i) {
currentStr += ')';
}
currentStr && result.push(currentStr);
return;
}
procedure(result,currentStr+'(',left+1,index+1,n);
if (index <= left * 2) {
procedure(result,currentStr+')',left,index+1,n);
}
};
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
var result = [];
procedure(result,'',0,1,n*2);
return result;
};
var procedure = function(result,currentStr,left,index,n) {
if (left >= n / 2) {
for (var i = index;i <= n;++i) {
currentStr += ')';
}
currentStr && result.push(currentStr);
return;
}
procedure(result,currentStr+'(',left+1,index+1,n);
if (index <= left * 2) {
procedure(result,currentStr+')',left,index+1,n);
}
};
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
var result = [];
procedure(result,'',0,1,n*2);
return result;
};