-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0301-RemoveInvalidParentheses.js
73 lines (63 loc) · 2.35 KB
/
0301-RemoveInvalidParentheses.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
//-----------------------------------------------------------------------------
// Runtime: 80ms
// Memory Usage: 38.6 MB
// Link: https://leetcode.com/submissions/detail/385885871/
//-----------------------------------------------------------------------------
var solution = function() {
'use strict';
/**
* @param {string} s
* @return {string[]}
*/
var removeInvalidParentheses = function(s) {
let invalidLeft = 0,
invalidRight = 0;
for (let ch of s) {
if (ch === '(') {
invalidLeft++;
} else if (ch === ')') {
invalidRight = invalidLeft === 0 ? invalidRight + 1 : invalidRight;
invalidLeft = invalidLeft === 0 ? invalidLeft : invalidLeft - 1;
}
}
var results = new Set();
DFS(s, 0, 0, 0, invalidLeft, invalidRight, '', results);
return Array.from(results);
};
/**
* @param {string} s
* @param {Number} index
* @param {Number} leftCount
* @param {Number} rightCount
* @param {Number} invalidLeft
* @param {Number} invalidRight
* @param {string} current
* @param {Set} results
*/
var DFS = function(s, index, leftCount, rightCount, invalidLeft, invalidRight, current, results) {
if (s.length === index) {
if (invalidLeft === 0 && invalidRight === 0) {
results.add(current);
}
return;
}
var ch = s[index];
if (ch === '(' && invalidLeft > 0) {
DFS(s, index + 1, leftCount, rightCount, invalidLeft - 1, invalidRight, current, results);
} else if (ch === ')' && invalidRight > 0) {
DFS(s, index + 1, leftCount, rightCount, invalidLeft, invalidRight - 1, current, results);
}
current += ch;
if (ch !== '(' && ch !== ')') {
DFS(s, index + 1, leftCount, rightCount, invalidLeft, invalidRight, current, results);
} else if (ch === '(') {
DFS(s, index + 1, leftCount + 1, rightCount, invalidLeft, invalidRight, current, results);
} else if (rightCount < leftCount) {
DFS(s, index + 1, leftCount, rightCount + 1, invalidLeft, invalidRight, current, results);
}
};
return {
removeInvalidParentheses: removeInvalidParentheses
};
};
module.exports = solution();