LeetCode-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 ).

题目大意

字符串中包含‘(’,‘)’以及其他字符,要删除最少的字符,使得该字符串成为合法的表达式,要求返回所有可能的结果。

示例

E1

Input: "()())()"
Output: ["()()()", "(())()"]

E2

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

E3

Input: ")("
Output: [""]

解题思路

先遍历一遍字符串,查找有几个不符合规范的‘(’以及‘)’。

再进行字符串的递归遍历,根据上边求得的不符合规范的数目,依次删除或保留当前的字符,最后符合条件的结果保留下来。

复杂度分析

时间复杂度:O(N2)

空间复杂度:O(N)

代码

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        int misl = 0, misr = 0;
        // 遍历字符串,查找不合法的‘(’以及‘)’的数目
        for(char c : s) {
            if(c == '(') {
                ++misl;
            }
            else if(c == ')'){
                if(misl)
                    --misl;
                else
                    ++misr;
            }
        }
        // set用来保留合法的结果,同时达到去重的效果
        set<string> ans;
        // 递归遍历字符串
        solve(s, ans, "", misl, misr, 0, 0);
        // 将set中保留的结果保存在vector中,返回结果
        vector<string> res;
        for(auto iter = ans.begin(); iter != ans.end(); ++iter) {
            res.push_back(*iter);
        }
        
        return res;
    }
    // s:输入的字符串
    // ans:合法的非重复的结果
    // exp:当前保留的合法的字符串
    // misl:‘(’不合法的数量
    // misr:‘)’不合法的数量
    // pair:应有的“()”成对的数量
    // i:遍历到的字符串s的位置
    void solve(const string& s, set<string>& ans, string exp, int misl, int misr, int pair, int i) {
        // 若遍历到最后
        if(i == s.length()) {
            // 若最后表达式合法,则将其保存再set中
            if(misl == 0 && misr == 0 && pair == 0)
                ans.insert(exp);
        }
        else {
            if(s[i] == '(') {
                // 如果还有不合法的‘(’,则将其删除
                if(misl) {
                    solve(s, ans, exp, misl - 1, misr, pair, i + 1);    
                }
                solve(s, ans, exp + '(', misl, misr, pair + 1, i + 1);
            }
            else if(s[i] == ')') {
                // 如果还有不合法的‘)’,则将其删除
                if(misr) {
                    solve(s, ans, exp, misl, misr - 1, pair, i + 1);
                }
                // 如果pair不为0,表示之前还有多余的‘(’
                if(pair)
                    solve(s, ans, exp + ')', misl, misr, pair - 1, i + 1);
            }
            else {
                solve(s, ans, exp + s[i], misl, misr, pair, i + 1);
            }
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/heyn1/p/11162352.html