|
| 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