Created
August 2, 2017 03:35
-
-
Save jianminchen/012faa9d471f00c85ef58f8d4b5aef10 to your computer and use it in GitHub Desktop.
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