Created
August 2, 2017 03:35
Leetcode 301 - remove invalid parenthesis -
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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