-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathgenerate-parentheses-ii.js
94 lines (83 loc) · 1.94 KB
/
generate-parentheses-ii.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
/**
* Generate Parentheses II
*
* Given n pairs of round brackets(parentheses), m pairs of square brackets and k pairs of curly brackets,
* write a function to generate all the combinations of well-formed brackets.
*
* Note: All of the brackets must be used.
*
* For example, given n = 1, m = 1, k = 1, a solution set is:
*
* [
* "()[]{}",
* "()[{}]",
* "(){[]}",
* "(){}[]",
* "([]){}",
* "([]{})",
* "([{}])",
* "({[]})",
* "({})[]",
* "({}[])",
* "[()]{}",
* "[(){}]",
* "[({})]",
* "[](){}",
* "[]({})",
* "[]{()}",
* "[]{}()",
* "[{()}]",
* "[{}()]",
* "[{}]()",
* "{()[]}",
* "{()}[]",
* "{([])}",
* "{[()]}",
* "{[]()}",
* "{[]}()",
* "{}()[]",
* "{}([])",
* "{}[()]",
* "{}[]()"
* ]
*/
import Stack from 'common/stack';
/**
* @param {number} n - n pairs of round brackets
* @param {number} m - m pairs of square brackets
* @param {number} k - k pairs of curly brackets
*
* @return {string[]}
*/
const generateBrackets = (n, m, k) => {
const lb = ['(', '[', '{'];
const rb = [')', ']', '}'];
const backtracking = (total, left, right, stack, solution) => {
if (total.join('') === left.join('') && total.join('') === right.join('') && solution) {
results.push(solution);
return;
}
for (let i = 0; i < 3; i++) {
// Add left brackets
if (left[i] < total[i]) {
stack.push(lb[i]);
left[i]++;
backtracking(total, left, right, stack, solution + lb[i]);
stack.pop();
left[i]--;
}
// Add right brackets
if (right[i] < left[i] && stack.peek() === lb[i]) {
stack.pop();
right[i]++;
backtracking(total, left, right, stack, solution + rb[i]);
stack.push(lb[i]);
right[i]--;
}
}
};
const results = [];
backtracking([n, m, k], [0, 0, 0], [0, 0, 0], new Stack(), '');
return results;
};
export default generateBrackets;