-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathGenerateParentheses.js
43 lines (37 loc) · 1.09 KB
/
GenerateParentheses.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
// Source : https://oj.leetcode.com/problems/generate-parentheses/
// Author : Dean Shi
// Date : 2015-06-12
/**********************************************************************************
*
* 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 {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
var strArr = [];
bfs('', 0, 0);
return strArr;
// breadth-first search algorithm
function bfs(str, left, right) {
if (left === n && right === n) {
strArr.push(str);
return;
}
if (left !== n) {
bfs(str + '(', left + 1, right);
}
if (left > right) {
bfs(str + ')', left, right + 1);
}
}
};
// Test case
console.log(generateParenthesis(3).toString() === '((())),(()()),(())(),()(()),()()()'); // true