301. Remove Invalid Parentheses(深度优先搜索)

本文介绍了一种使用深度优先搜索解决LeetCode上移除无效括号问题的方法。通过遍历字符串并根据括号匹配情况调整搜索方向,实现对非法括号的有效移除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://leetcode.com/problems/remove-invalid-parentheses/

1. 思路

用深度优先搜索的思路,遍历这个字符串,当出现“)”的个数多于“(”的个数时,开始删除之前遇到的“)”使之平衡。每次平衡之后继续往后遍历,直到结束。当出现“(”的个数多于“)”的个数时,不能直接删除之前遇到的“(”,这时把字符串reverse之后按照刚才的操作。

2. 细节

1)如果碰到不匹配的括号,不作删除处理的话整个字符串旧没有必要再遍历了,记得加个break。否则可能导致找到所有答案之后还继续往下找

2)字符串翻转之前如果发现已经平衡,没有必要翻转

3)字符串翻转之后:"()())()" =》 ")()(()(",这时要去除的符号是“(”

3. AC 代码

class Solution {
public:
    vector<string> removeInvalidParentheses(string s) {
        int count=0, i=0, j=0;
        bool reversed=false;
        vector<string> res;
        dfs(s, count, reversed, i, j, res, '(', ')');
        return res;
    }
    void dfs(string s, int count, bool& reversed, int first, int second, vector<string>& res, char left, char right){
        for(int i=first; i<s.size(); i++){
            if(s.at(i) == left) count += 1;
            else if(s.at(i) == right) count -= 1;
            if(count<0){
                for(int j=second; j<=i; j++){
                    if(s.at(j) == right && (j==0 || s.at(j-1) != right)){
                        string tmp = s.substr(0, j)+s.substr(j+1, s.size()-j-1);
                        dfs(tmp, count+1, reversed, i, j, res, left, right);
                    }
                }
                break;
            }
        }
        if(reversed == false && count==0){
            res.push_back(s);
        }
        else if(reversed == true && count==0){
            reverse(s.begin(), s.end());
            res.push_back(s);
        }
        else if(reversed == false && count>0){
            reverse(s.begin(), s.end());
            reversed = true;
            int i=0, j=0, count=0;
            dfs(s, count, reversed, i, j, res, right, left);
            reversed = false;
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值