注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
LC 301. Remove Invalid Parentheses
solution: 0ms 100.00%, 9.3MB 95.83%
class Solution {
public:
vector<string> removeInvalidParentheses(string s) {
/// recursion forward (')') and backward ('(')
vector<string> res;
remove_invalid(s, 0, 0, {'(', ')'}, res);
return res;
}
void remove_invalid(const string& s, int last_idx, int last_rem,
const vector<char>& bracket, vector<string>& res) {
int cnt = 0; // count of the first bracket
for (int i = last_idx; i < s.size(); ++i) {
if (s[i] == bracket[0]) ++cnt;
else if (s[i] == bracket[1]) --cnt;
if (cnt >= 0) continue; // no obvious violation yet
// bracket[1] violates, remove
for (int j = last_rem; j <= i; ++j) {
if (s[j] == bracket[1] && (j == last_rem || s[j] != s[j-1])) {
remove_invalid(s.substr(0, j) + s.substr(j+1), i, j, bracket, res);
}
}
// all done. don't need to go back.
return;
}
// up to here meaning need to remove extra left brackets
// A trick is used to reverse the string and treat '(' as ')'.
string s_rev = string(s.rbegin(), s.rend());
if (bracket[0] == '(') remove_invalid(s_rev, 0, 0, { ')', '(' }, res);
else res.push_back(s_rev); // save result (must've been reversed twice already)
}
};
-----------------------------------------
Space 应该是O(N)吧(for string s_rev)?
Time呢?O(2 * N^2) ??
|