301. 删除无效的括号

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-invalid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


使用一个参数,代替了两个参数,记录左右括号的个数。左括号:值+1;右括号:值-1;

    // 很容易陷入这个题的思维,就是删除最小的数量,
    // 换一种思想,就是给你个字符串拼接最长的合法括号字符串

    List<String> list = new ArrayList<>();
    int maxLength = -1;
    public List<String> removeInvalidParentheses(String s) {

        dfs(s,0,"",0);
        return list;
    }

    public void dfs(String s, int index, String str,int count) {
        // 右括号数量多了,肯定不符合条件了
        if(count < 0) {
            return;
        }
        // 遍历结束了
        if(index == s.length()) {
            // 如果此时没有达到平衡,返回。
            if(count !=0) {
                return;
            }
            // 达到平衡后,更新最大值。
            if(str.length() > maxLength) {
                maxLength = str.length();
                list.clear();
            }
            if(str.length() == maxLength)  {
                if(!list.contains(str)) {
                     list.add(str);
                }
            }
            return;
        }
        // 当前位置:拼接或者不拼接

        // 拼接
        char ch = s.charAt(index);
        if(ch == '(') {
            dfs(s,index +1,str + ch, count+1);
            


        } else if(ch == ')') {
            dfs(s,index +1,str + ch, count-1);
        } else {
            dfs(s,index +1,str + ch, count);

        }
        // 不拼接
        dfs(s,index+1,str,count);

    }
posted @ 2022-02-28 19:28  一颗青菜  阅读(8)  评论(0)    收藏  举报