-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.parenthesis.js
More file actions
42 lines (37 loc) · 904 Bytes
/
string.parenthesis.js
File metadata and controls
42 lines (37 loc) · 904 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
/*
* @title: Generate valid parenthesis
* @description: Generate valid parenthesis combinations
* @author: Thorsten Kober
* @email: [email protected]
*/
function generateParenthesis(n) {
const result = [];
function generate(current, open, close, n) { // eslint-disable-line
if (current.length === n * 2) {
result.push(current);
return;
}
if (open < n) {
generate(`${current}(`, open + 1, close, n);
}
if (close < open) {
generate(`${current})`, open, close + 1, n);
}
}
generate('', 0, 0, n);
return result;
}
// npx jest algorithms/string/string.parenthesis.js
describe('generate parenthesis up to given number', () => {
test('generateParenthesis()', () => {
expect(generateParenthesis(3)).toEqual(
[
'((()))',
'(()())',
'(())()',
'()(())',
'()()()',
],
);
});
});