您的位置:首页 > 其它

Remove Invalid Parentheses

2016-03-11 01:34 344 查看
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())()"]
")(" -> [""]
[code]class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
set<string> temp;
int n = s.length();

int left_remove = 0;
int right_remove = 0;
for (int i = 0; i < n; i++)
{
if (s[i] == '(')
{
left_remove++;
}
else if (s[i] == ')')
{
if (left_remove > 0)
{
left_remove--;
}
else
{
right_remove++;
}
}
}
visit(s, n, 0, left_remove, right_remove, 0, 0, "", temp);

vector<string> result(temp.begin(), temp.end());

return result;
}
private:
void visit(string &s, int n, int pos, int left_remove, int right_remove,
int left_count, int right_count, string buf, set<string> &temp)
{
if (n == pos)
{
if (left_remove == 0 && right_remove == 0)
{
temp.insert(buf);
}
return;
}

if (s[pos] == '(')
{
if (left_remove > 0)
{
visit(s, n, pos+1, left_remove-1, right_remove, left_count, right_count, buf, temp);
}
visit(s, n, pos+1, left_remove, right_remove, left_count+1, right_count, buf+s[pos], temp);
}
else if (s[pos] == ')')
{
if (right_remove > 0)
{
visit(s, n, pos+1, left_remove, right_remove-1, left_count, right_count, buf, temp);
}
if (left_count <= right_count)
{
return;
}
visit(s, n, pos+1, left_remove, right_remove, left_count, right_count+1, buf+s[pos], temp);
}
else
{
visit(s, n, pos+1, left_remove, right_remove, left_count, right_count, buf+s[pos], temp);
}
}
};

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: