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

Example 1:

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

Example 2:

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

Example 3:

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

给定一个字符串,包含‘(’和‘)’和其他字符,求出除去最少的字符使得括号匹配的所有可能的字符串。首先需要计算最少需要除去多少个左括号和右括号,然后调用递归,并且在除去了最少数目的字符之后再判断得到的结果是否为合法的括号匹配。

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        vector<string> result;
        int left=0;
        int right=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(') left++;
            else if(s[i]==')')
            {
                if(left==0) right++;
                else left--;
            }
        }
        get_valid_parentheses(s,0,left,right,result);
        return result;
    }
    
    void get_valid_parentheses(string s, int i, int left, int right, vector<string>& result)
    {
        if(left<0||right<0) return;
        else if(left==0&&right==0)
        {
            if(isValid(s)) result.push_back(s);
            return;
        }

        for(int j=i;j<s.size();j++)
        {
            string temp=s;
            if(j>0&&s[j]==s[j-1]) continue;
            else if(s[j]=='('&&left>0)
                get_valid_parentheses(temp.erase(j,1),j,left-1,right,result);
            else if(s[j]==')'&&right>0)
                get_valid_parentheses(temp.erase(j,1),j,left,right-1,result);
        }
    }
    
    bool isValid(string s)
    {
        int count=0;
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='(') count++;
            else if(s[i]==')') count--;
            if(count<0) return false;
        }
        if(count==0) return true;
        else return false;
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值