LeetCode题解——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())()"]
")(" -> [""]

解题思路: 

1. 如果给我们一个字符串,首先去掉不合法的首字符即')'以及不合法的尾字符‘(’, 将其变为以‘(’开头,以‘)’结尾的字符串: (.......)

2. 对这个字符串,我们需要统计它有多少个不合法的‘(’,以及‘)’,分别用num1和num2表示。

3. batracking, 我们每次判断去掉一个字符后的字符串是否是合法字符串,是的话那么将该字符串存入结果字符,并递归回溯。 否则,继续处理。

class Solution {
public:
    vector<string> removeInvalidParentheses(string& s) {
        vector<string> ret;
        int num1 = 0, num2 = 0, sum = 0;
        int beg = 0, end = s.size()-1;
        while(s[beg]==')') beg++;
        while(s[end]=='(') end--;
        s = s.substr(beg,end-beg+1);
        for(int i=0 ;i<s.size();i++){
            if(s[i]=='(') sum++;
            else if(s[i]==')') sum--;
            num2 = min(num2,sum);
        }
        num1 = sum - num2;
        removeInvalidParentheses(s,0,num1,num2,ret);
        return ret;
    }
    bool isValid(string s) {
        int sum = 0;
        for(auto &c : s)        //check whether s is valid or not
        {
            if(c == '(') ++sum;
            else if(c == ')') --sum;
            if(sum < 0) return false;
        }
        return sum == 0;
    }
    void removeInvalidParentheses(string s,int beg, int num1, int num2, vector<string>& ret){
        if(num1==0 && num2 == 0)
        {   
            if(isValid(s))
                ret.push_back(s);
            return;
        }
        for(int i = beg; i < s.size(); ++i)
        {
            string tmp = s;
            /*
            The num2 == 0 expression is hard to come up with. All invalid '('
                can only appear after invalid ')', otherwise 
                there is no invalid ')'. It's OK we don't add
                this num2 == 0 test, without which only slows
                down the performance a little bit, from 4ms to 12ms.
           */
            if(num2 == 0 && num1 > 0 && tmp[i] == '(')    
            {
                if(i == beg || tmp[i] != tmp[i - 1])   //Watch here! This is the trick to avoid duplicates.
                {
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, num1 - 1, num2, ret);
                }
            }
            if(num2 < 0 && tmp[i] == ')')
            {
                if(i == beg || tmp[i] != tmp[i - 1])
                {
                    tmp.erase(i, 1);
                    removeInvalidParentheses(tmp, i, num1, num2 + 1, ret);
                }
            }
        }
    }
};





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值