-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22GenerateParentheses.js
More file actions
44 lines (38 loc) · 944 Bytes
/
Copy path22GenerateParentheses.js
File metadata and controls
44 lines (38 loc) · 944 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
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let output = [];
function backTrack(output,current, open, close){
if(current.length == n*2){
output.push(current);
return;
}
if(open<n) backTrack(output, current +"(", open +1, close);
if(close < open) backTrack(output, current+")", open, close+1); //if close>open: invalid
}
backTrack(output, "",0,0);
return output;
};
//조건에 맞는 걸 '다' 탐색하고 다시 그 전 걸로 돌아옴
var generateParenthesis2 = function(n) {
let res = [];
function generate(open, close, str){
if(close>open){
return;
}
if(close == n && open == n){
res.push(str);
return;
}
if(open < n){
generate(open+1, close, str + "(")
}
if(close<open){
generate(open, close+1, str + ")");
}
}
generate(0,0,'');
return res;
};