题目描述
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 ).
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:
Input: ")("
Output: [""]
思路
合法的括号串,在任意位置,左括号数量大于等于右括号数量。统计左括号和右括号数量,当没有左括号和右括号抵消时,该右括号需要被删除。最后剩下的左括号需要被删除。统计得到需要删除的左括号和右括号数量。
然后DFS,需要删掉l个左括号和r个右括号。从当前位置往后遍历,作为被删除的括号。
代码
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
int l = 0, r = 0;
int len = s.length();
for (int i=0; i<len; ++i) {
if (s[i] != '(' && s[i] != ')') continue;
if (s[i] == '(') l++;
else if (s[i] == ')' && l > 0) l--;
else r++;
}
vector<string> ans;
dfs(s, 0, l, r, ans);
return ans;
}
bool valid(string s) {
int cnt = 0;
for (int i=0; i<s.length(); ++i) {
if (s[i] != '(' && s[i] != ')') continue;
if (s[i] == '(') cnt++;
else cnt--;
if (cnt < 0) return false;
}
return cnt == 0;
}
void dfs(string& s, int st, int l, int r, vector<string>& ans) {
if (l == 0 && r == 0) {
if (valid(s)) ans.push_back(s);
return;
}
for (int i=st; i<s.length(); ++i) {
if (i != st && s[i] == s[i-1]) continue;
if (s[i] != '(' && s[i] != ')') continue;
string p = s;
char ch = p[i];
p.erase(i, 1);
if (l > 0 && ch == '(') dfs(p, i, l-1, r, ans);
if (r > 0 && ch == ')') dfs(p, i, l, r-1, ans);
}
return;
}
};
第二次写了。。。。还是觉得很难。。。。。
本文介绍了一种算法,用于移除字符串中最小数量的无效括号,使其成为有效的括号串。通过深度优先搜索(DFS)策略,算法统计并移除多余的左括号和右括号,返回所有可能的有效结果。

7420

被折叠的 条评论
为什么被折叠?



