您的位置:首页 > 其它

LeetCode Remove Invalid Parenthese

2015-11-17 22:17 169 查看
LeetCode 每日刷题!!

Remove Invalid Parentheses

这道题在做的时候用到了BFS因为它要求的是最优解

层次依次为删除0个元素,1个元素,2个元素。。。

如果在一层找到符合要求的就返回

在做的时候考虑效率问题,要对BFS进行剪枝,不然会timelimit, 使用的方法一:出现过的就加入visited里面不再加入叶子节点,二:visited用hash,提高查找效率

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <unordered_set>
#include <queue>
#include <stack>
#include <assert.h>
#include <set>
using namespace std;

class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
set<string> visited;
string *current = &s;
vector<string> ans;
vector<string> layerSet;
vector<string> nextlayer;
if (s == "")
{
ans.push_back("");
return ans;
}
layerSet.push_back(s);

while (layerSet.size() != 0)
{
//each layer of a BFT, the optimize have the least delete number
//and each loop have the same delete num.
for (int i = 0; i < layerSet.size(); i++)
{
*current = layerSet[i];
if (isValid(*current))
{
ans.push_back(*current);
}

}
if (ans.size() != 0)
{
return ans;
}
for (int i = 0; i < layerSet.size(); i++)
{
*current = layerSet[i];
for (int i = 0; i < current->size(); i++)
{
if ((*current)[i] != '(' && (*current)[i] != ')')
{
continue;
}
string tmp = current->substr(0, i) + current->substr(i + 1);
if (tmp == "")
{
ans.push_back("");
return ans;
}

if (visited.find(tmp) == visited.end())
{
nextlayer.push_back(tmp);
visited.insert(tmp);
}

}
}
layerSet.swap(nextlayer);

}
return ans;
}

bool isValid(string s)
{
int num = 0;
if (s.size() == 0)
{
return false;
}
for (int i = 0; i < s.size(); i++)
{
if (s[i] == '(') {
num++;
}
if (s[i] == ')') {
num--;
}
if (num < 0)
return false;
}
return num == 0;
}
};

int main()
{
string test1 = ")()m)(((()((()((((";
vector<string> ans;
Solution *solu = new Solution();
ans = solu->removeInvalidParentheses(test1);
for (int i = 0; i < ans.size(); i++)
{
cout << ans[i] << endl;
}

system("pause");
return 0;

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