您的位置:首页 > 编程语言 > C语言/C++

leetcode 301 : Remove Invalid Parentheses

2015-11-06 21:14 295 查看
1、原题如下:

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 ).

Examples:

“()())()” -> [“()()()”, “(())()”]

“(a)())()” -> [“(a)()()”, “(a())()”]

“)(” -> [“”]

2、解题如下:

class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
unordered_set<string> result;
int left_erase=0;
int right_erase=0;
for(auto c:s)
{
if(c=='(') {left_erase++;}
if(c==')')
{
if(left_erase!=0)
left_erase--;
else
right_erase++;
}
}
traverse(s,0,left_erase,right_erase,0,"",result);
return vector<string> (result.begin(),result.end());
}
void traverse(string s,int count,int left_erase,int right_erase,int pair,string tmp,unordered_set<string>& result)
{
if(count==s.size())
{
if(left_erase==0&&right_erase==0&&pair==0)
result.insert(tmp);
return;
}
if(s[count]!='('&&s[count]!=')')
{
traverse(s,count+1,left_erase,right_erase,pair,tmp+s[count],result);
}
else if(s[count]=='(')
{
if(left_erase>0)
{
traverse(s,count+1,left_erase-1,right_erase,pair,tmp,result);
}
traverse(s,count+1,left_erase,right_erase,pair+1,tmp+s[count],result);
}
else
{
if(right_erase>0)
{
traverse(s,count+1,left_erase,right_erase-1,pair,tmp,result);
}
if(pair>0)
{
traverse(s,count+1,left_erase,right_erase,pair-1,tmp+s[count],result);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++ 面试