[LeetCode] 301. Remove Invalid Parentheses

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

题目大意

除去表达式中最少的’(‘或’)’,使表达式 括号匹配。

思路

bdfs + 减枝
首先统计出 需要 删除的 ‘(’ 数量 和 ‘)‘数量。
然后 用 bdfs删除,在删除中若发现当前stringbuilder 中 ‘(’ 的数量大于 ‘)’ ,剪枝。
由于 需要去重 “((” 中 只能取前一个,使用hasVisited[i-1] ==false 筛查,若为对那么添加下’(’,否则不添加。

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        int l=0,r=0;
        for(char ch : s.toCharArray()){
            if(ch == '(')
                l++;
            else if(ch == ')'){
                if(l!=0)
                    l--;
                else
                    r++;
            }
        }
        StringBuilder curRes = new StringBuilder();
        List<String> resList =new ArrayList<>();
        boolean[] hasVisited = new boolean[s.length()];
        bdfs(s,0,resList,curRes,l,r,0,hasVisited);
        return resList;
    }
    void bdfs(String s, int i ,List<String> resList,StringBuilder curRes,int l,int r,int cnt,boolean[] hasVisited){

        if(s.length() == i && l == 0 &&  r == 0 && cnt == 0){
            resList.add(curRes.toString());
            return ;
        }
        if(s.length()<=i || l<0 || r<0 || cnt <0)
            return ;
        char curCh = s.charAt(i);


        if(curCh == '('){
            bdfs(s,i+1,resList,curRes,l-1,r,cnt,hasVisited);
            if(i>0 && curCh == s.charAt(i-1) && hasVisited[i-1] == false)
                return;
            hasVisited[i] = true;
            curRes.append(curCh);
            bdfs(s,i+1,resList,curRes,l,r,cnt+1,hasVisited);
            curRes.deleteCharAt(curRes.length()-1);
            hasVisited[i] = false;

        }else if(curCh == ')'){
            bdfs(s,i+1,resList,curRes,l,r-1,cnt,hasVisited);
            if(i>0 && curCh == s.charAt(i-1) && hasVisited[i-1] == false)
                return;
            hasVisited[i] = true;
            curRes.append(curCh);
            bdfs(s,i+1,resList,curRes,l,r,cnt-1,hasVisited);
            curRes.deleteCharAt(curRes.length()-1);
            hasVisited[i] = false;

        }else{
            curRes.append(curCh);
            bdfs(s,i+1,resList,curRes,l,r,cnt,hasVisited);
            curRes.deleteCharAt(curRes.length()-1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值