301. Remove Invalid Parentheses 去掉不合理的括号

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())()"]
")(" -> [""]


T(n) = n x C(n, n) + (n-1) x C(n, n-1) + ... + 1 x C(n, 1) = n x 2^(n-1).

class Solution {
public:
bool isvalid(string s){
int count = 0;
for(int i = 0; i < s.size(); i++){
if(s[i] == '(')
count++;
else if(s[i] == ')')
count--;
if(count < 0)
return false;
}
return count == 0;
}

vector<string> removeInvalidParentheses(string s) {
set<string> sets;
vector<string>res;
queue<string>q;
q.push(s);
sets.insert(s);
bool found =false;
while(!q.empty()){
string str = q.front();
q.pop();
if(isvalid(str)){
res.push_back(str);
found = true;
}
if(found) continue;
for(int i = 0; i < s.size(); i++){
if(str[i] == '(' || str[i] == ')'){
string strs = str.substr(0,i) + str.substr(i+1);
if(sets.find(strs) == sets.end()){
sets.insert(strs);
q.push(strs);
}
}
}
}
return res;
}
};

LeetCode 301. Remove Invalid Parentheses（删除无效的括号）

2016-04-19 04:44:37

leetcode -- Remove Invalid Parentheses--又是DFS,BFS的题目

2015-12-25 17:00:13

[leetcode] 301. Remove Invalid Parentheses 解题报告

2015-12-26 16:00:49

301. Remove Invalid Parentheses （Hard）

2017-04-11 19:36:34

[leetcode] 301. Remove Invalid Parentheses

2016-02-18 10:44:15

【Leetcode】301. Remove Invalid Parentheses 移除非法小括号

2017-02-21 12:32:38

[LeetCode] Remove Invalid Parentheses

2015-11-09 16:45:57

301. Remove Invalid Parentheses

2016-01-26 16:27:51

[LeetCode]--301. Remove Invalid Parentheses

2016-08-18 21:13:16

301. Remove Invalid Parentheses（BFS）

2018-01-07 23:55:01

不良信息举报

301. Remove Invalid Parentheses 去掉不合理的括号