【LeetCode 301】Remove Invalid Parentheses

题意:

给一个可能包含小写字母的括号串,求出在去掉最少括号之后的所有合法串。

思路:

dfs。统计括号,需要删除字符时,从上次遍历到的位置到当前位置,尝试所有可以删除的字符,递归到下一问题。

代码:

class Solution {
public:
    vector<string> ans;
    
    vector<string> removeInvalidParentheses(string s) {
        dfs(s, ')', 0);
        return ans;
    }
    
    void dfs(string s, char pa, int last) {
        for (int i=0, cnt=0; i<s.length(); ++i) {
            if (s[i] == '(' || s[i] == ')') s[i] == pa ? cnt++ : cnt--;
            if (cnt <= 0) continue;
            for (int j=last; j<=i; ++j) {
                if (s[j] == pa && (j == last || s[j-1] != pa)) {
                    dfs(s.substr(0, j)+s.substr(j+1), pa, j);
                }
            }
            return;
        }
        
        reverse(s.begin(), s.end());
        if (pa == ')') dfs(s, '(', 0);
        else ans.push_back(s);
        return;
    }
};

很难。看了好久。
参考链接:https://blog.csdn.net/qq508618087/article/details/50408894

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/91808349