https://leetcode.com/problems/remove-invalid-parentheses/description/
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
又是一道经典题。
算法用BFS,
data structure:queue,unordered_set
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
vector<string>res;
if(s.size() < 1)
{
res.push_back(s);
return res;
}
queue<string>q;
unordered_set<string>tovisit;
q.push(s);
tovisit.insert(s);
bool found = false;
while(!q.empty())
{
string cur = q.front();
q.pop();
if(isvalid(cur))
{
res.push_back(cur);
found = true;
}
//the found is to avoid further search once found since the goal is to remove the minimun invalid
//use "continue" instead of "break" is to search the same level since the goal is to dump all possible result
if(found == true)
{
continue;
}
for(int i = 0; i < cur.size(); i++)
{
if(cur[i] != '(' && cur[i] != ')') continue;
string newstr = cur.substr(0,i) + cur.substr(i+1);
if(tovisit.find(newstr) == tovisit.end())
{
tovisit.insert(newstr);
q.push(newstr);
}
}
}
return res;
}
bool isvalid(string str)
{
int count = 0;
for(auto c : str)
{
if(c == '(')
{
count ++;
}
else if(c == ')')
{
if(count == 0)
{
return false;
}
count --;
}
}
return count == 0;
}
};