# 301. Remvoe Invalid Parenthesis

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

**Note:** The input string may contain letters other than the parentheses`(`and`)`.

**Example 1:**

```
Input:
 "()())()"

Output:
 ["()()()", "(())()"]
```

**Example 2:**

```
Input:
 "(a)())()"

Output:
 ["(a)()()", "(a())()"]
```

**Example 3:**

```
Input:")("

Output: [""]
```

**Facebook Variation: any solution that results in minimum removal of parentheses**&#x20;

**Thoughts**: 楼主用了一个3-pass的方法: 先从头到尾找close比open多的，移掉; 从尾到头找open比close多的，移掉; 然后最后一遍build

```python
class Solution:
    def removeInvalidParentheses(self, s):
        cnt = 0
        idx = []
        ans = ''
        # forward to remove close first
        for i, c in enumerate(s):
            if c == '(':
                cnt += 1
            if c == ')':
                cnt -= 1
                if cnt < 0:
                    idx.append(i)
                    cnt = 0  # reset the cnt
        cnt = 0
        # reverse to remove open first
        for i, c in enumerate(s[::-1]):
            if c == ')':
                cnt += 1
            if c == '(':
                cnt -= 1
                if cnt < 0:
                    idx.append(len(s) - i - 1)
                    cnt = 0
        return ''.join([s[i] for i in range(len(s)) if i not in idx])

s1= Solution()
print(s1.removeInvalidParentheses(""))
print(s1.removeInvalidParentheses("("))
print(s1.removeInvalidParentheses(")"))
print(s1.removeInvalidParentheses("(()"))
print(s1.removeInvalidParentheses("(()))"))
```

**Thoughts:**&#x20;

1. Expanding the set and test whether each combination is valid, once there is answer in the set , then return (we want the minimum edition)

**Code: Python**

```python
class Solution:
    def removeInvalidParentheses(self, s):
        def isvalid(s):
            ctr = 0
            for c in s:
                if c == '(':
                    ctr += 1
                elif c == ')':
                    ctr -= 1
                    if ctr < 0:
                        return False
            return ctr == 0
        level = {s}
        while True:
            res = filter(isvalid, level)
            if res:
                return res
            level = {s[:i] + s[i+1:] for s in level for i in range(len(s))}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://code.taozirui.com/lc/parentheses/remvoe-invalid-parenthesis.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
