Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jianminchen/012faa9d471f00c85ef58f8d4b5aef10 to your computer and use it in GitHub Desktop.
Save jianminchen/012faa9d471f00c85ef58f8d4b5aef10 to your computer and use it in GitHub Desktop.
Leetcode 301 - remove invalid parenthesis -
class Solution {
public:
void DFS(string s, char ch, int last)
{
for(int i = 0, cnt = 0; i < s.size(); i++)
{
if(s[i]=='('||s[i]==')') s[i]==ch?cnt++:cnt--;
if(cnt <= 0) continue;
for(int j = last; j <= i; j++)
{
if(s[j] == ch && (j ==last || s[j-1]!= ch))
DFS(s.substr(0, j)+s.substr(j+1), ch, j);
}
return;
}
reverse(s.begin(), s.end());
if(ch == ')') return DFS(s, '(', 0);
ans.push_back(s);
}
vector<string> removeInvalidParentheses(string s) {
DFS(s, ')', 0);
return ans;
}
private:
vector<string> ans;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment