Leetcode 22 - Generate parentheses

Note:

  • Use backtracking to find all valid combinations.
  • Have to prune unqualified branches, otherwise TLE.

Question:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example:

1
2
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Code:

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
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
const parentheses = ['(', ')'];
let result = [];
let path = [];
dfs(parentheses, n);
return result;

function dfs(parentheses, n) {
if (path.length === n * 2) {
if (checkValidity(path)) {
result.push(path.join(''));
}
return;
}
for (let i = 0; i < parentheses.length; i++) {
if (!countParentheses(path, n)) continue;
path.push(parentheses[i]);
dfs(parentheses, n);
path.pop();
}
}

function countParentheses(arr, n) {
let leftParenthesis = 0;
let rightParenthesis = 0;
for (const char of arr) {
if (char === '(') {
leftParenthesis++;
if (leftParenthesis > n) return false;
} else {
rightParenthesis++;
if (rightParenthesis > n) return false;
}
}
return true;
}

function checkValidity(arr) {
let stack = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] === '(') {
stack.push(arr[i]);
} else {
if (stack.length === 0) return false;
stack.pop();
}
}
return stack.length === 0;
}
};