301. Remove Invalid Parentheses

本文探讨了一个利用回溯算法解决去除无效括号问题的方法,详细介绍了辅助函数findNumToRemove的作用以及backtracking的核心步骤。同时,文章强调了在实现过程中需要注意的关键点,如确保括号序列合法、避免重复结果以及正确处理不同字符类型。

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

Problem

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())()"]
")(" -> [""]


Solution 

一开始看到这道题卡住了敲打敲打敲打

最主要是没想到这个辅助函数 findNumToRemove , 来算出要删除左括号和右括号的个数 ( rmLeft 和 rmRight).

得到这两个变量就好办了,就是典型的backtracking :遇到左括号,要么删除(rmLeft - 1), 要么就加到一个可能的结果里; 右括号同理;其它字符就照收

还需要注意几点:
1. 需要一个变量 open来确保是合法的一系列括号。
2. 需要用unordered_set 来存结果,因为有可能重复。


class Solution {
    void findNumToRemove(const string& str, int& rmLeft, int& rmRight){
        for( char c : str){
            if( c == '(' ){
                rmLeft++;
            }
            else if( c == ')' ){
                if(rmLeft > 0) {
                    rmLeft--;
                }
                else {
                    rmRight++;
                }
            }
        }
    }
    
    void helper( const string& str, int rmLeft, int rmRight, int idx, int open,string oneRst, set<string>& rst){
        if(idx == str.size() && rmLeft == 0 && rmRight == 0 && open == 0){
            rst.insert(oneRst);
            return;
        }
        if(rmLeft < 0 || rmRight < 0 || idx == str.size() || open < 0 ) return;
        
        char c = str[idx];
        if( c == '(' ) {
            helper(str, rmLeft, rmRight, idx + 1, open + 1, oneRst + c, rst); // take it
            helper(str, rmLeft - 1, rmRight, idx + 1, open, oneRst, rst);     // remove it
        }
        else if( c == ')' ) {
            helper(str, rmLeft, rmRight, idx + 1, open - 1, oneRst + c, rst); //take it
            helper(str, rmLeft, rmRight - 1, idx + 1, open , oneRst, rst);    //remove it
        }
        else {
            helper(str, rmLeft, rmRight, idx + 1, open, oneRst + c, rst);
        }
    }
    
public:
    vector<string> removeInvalidParentheses(string s) {
        int rmLeft = 0, rmRight = 0;
        findNumToRemove(s, rmLeft, rmRight);
        
        set<string> rst;
        helper(s, rmLeft, rmRight, 0, 0, string(), rst);
        
        return vector<string> (rst.begin(), rst.end());
    }
};

This solution inspired me :   https://leetcode.com/discuss/72208/easiest-9ms-java-solution

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值