Skip to content

Commit 46bf946

Browse files
committed
Add solution #301
1 parent 391e54c commit 46bf946

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@
246246
297|[Serialize and Deserialize Binary Tree](./0297-serialize-and-deserialize-binary-tree.js)|Hard|
247247
299|[Bulls and Cows](./0299-bulls-and-cows.js)|Medium|
248248
300|[Longest Increasing Subsequence](./0300-longest-increasing-subsequence.js)|Medium|
249+
301|[Remove Invalid Parentheses](./0301-remove-invalid-parentheses.js)|Hard|
249250
303|[Range Sum Query - Immutable](./0303-range-sum-query-immutable.js)|Easy|
250251
306|[Additive Number](./0306-additive-number.js)|Medium|
251252
309|[Best Time to Buy and Sell Stock with Cooldown](./0309-best-time-to-buy-and-sell-stock-with-cooldown.js)|Medium|
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* 301. Remove Invalid Parentheses
3+
* https://leetcode.com/problems/remove-invalid-parentheses/
4+
* Difficulty: Hard
5+
*
6+
* Given a string s that contains parentheses and letters, remove the minimum number of
7+
* invalid parentheses to make the input string valid.
8+
*
9+
* Return a list of unique strings that are valid with the minimum number of removals.
10+
* You may return the answer in any order.
11+
*/
12+
13+
/**
14+
* @param {string} s
15+
* @return {string[]}
16+
*/
17+
var removeInvalidParentheses = function(s) {
18+
const result = new Set();
19+
let minRemoved = Infinity;
20+
21+
backtrack(s, 0, 0, 0, 0, '');
22+
23+
return Array.from(result);
24+
25+
function backtrack(str, index, open, close, removed, curr) {
26+
if (index === s.length) {
27+
if (open === close && removed <= minRemoved) {
28+
if (removed < minRemoved) {
29+
result.clear();
30+
minRemoved = removed;
31+
}
32+
result.add(curr);
33+
}
34+
return;
35+
}
36+
37+
if (s[index] !== '(' && s[index] !== ')') {
38+
backtrack(str, index + 1, open, close, removed, curr + s[index]);
39+
} else {
40+
backtrack(str, index + 1, open, close, removed + 1, curr);
41+
if (s[index] === '(') {
42+
backtrack(str, index + 1, open + 1, close, removed, curr + '(');
43+
} else if (close < open) {
44+
backtrack(str, index + 1, open, close + 1, removed, curr + ')');
45+
}
46+
}
47+
}
48+
};

0 commit comments

Comments
 (0)