美文网首页
301. 删除无效的括号

301. 删除无效的括号

作者: justonemoretry | 来源:发表于2021-09-23 22:19 被阅读0次
image.png

解法

class Solution {

    private char[] charArray;
    private Set<String> res = new HashSet<>();

    public List<String> removeInvalidParentheses(String s) {
        charArray = s.toCharArray();
        // 左右括号最少移除数
        int leftMove = 0;
        int rightMove = 0;
        for (char c : charArray) {
            if (c == ')') {
                if (leftMove > 0) {
                    leftMove--;
                } else {
                    rightMove++;
                }
            } else if (c == '(') {
                leftMove++;
            }
        }
        dfs(0, 0, 0, leftMove, rightMove, new StringBuilder());
        return new ArrayList<>(res);
    }

    private void dfs(int index, int leftCount, int rightCount, int leftMove, int rightMove, StringBuilder path) {
        // index到达末尾,且左右括号最小移除数是0
        if (index == charArray.length) {
            if (leftMove == 0 && rightMove == 0) {
                res.add(path.toString());
            }
            return;
        }
        char c = charArray[index];
        // 尝试删除
        if (c == '(' && leftMove > 0) {
            dfs(index + 1, leftCount, rightCount, leftMove - 1, rightMove, path);
        }
        if (c == ')' && rightMove > 0) {
            dfs(index + 1, leftCount, rightCount, leftMove, rightMove - 1, path);
        }
        // 尝试保留
        path.append(c);
        if (c != '(' && c != ')') {
            dfs(index + 1, leftCount, rightCount, leftMove, rightMove, path);
        } else if (c == '(') {
            dfs(index + 1, leftCount + 1, rightCount, leftMove, rightMove, path);
        } else if (leftCount > rightCount) {
            // 保留右括号时,左边大于右边才合法
            dfs(index + 1, leftCount, rightCount + 1, leftMove, rightMove, path);
        }
        path.deleteCharAt(path.length() - 1);
    }
}

相关文章

  • 301. 删除无效的括号

    【Description】删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。 说明: 输入可能包含...

  • 301. 删除无效的括号

    这道题我个人认为比较经典,里边的思路值得学习一开始我用回溯的思路没搞出来,参考网友的写了一版。。。

  • 301. 删除无效的括号

    解法

  • 【LeetCode】301. 删除无效的括号

    给你一个由若干括号和字母组成的字符串 s ,删除最小数量的无效括号,使得输入的字符串有效。 返回所有可能的结果。答...

  • 删除无效的括号

    题目描述:删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。说明: 输入可能包含了除 ( 和 ) ...

  • 删除无效的括号

    来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/remove...

  • 力扣 301 删除无效的括号

    题意:给定一个字符串找出删除最少非法字符串的所有组合 思路: 遍历括号,找出合法的括号个数 利用递归,遍历每一个子...

  • 移除无效的括号

    题目: 给你一个由 '('、')' 和小写字母组成的字符串 s。你需要从字符串中删除最少数目的 '(' 或者 ')...

  • AFNetworking.framework Command /

    尝试解决方法: clean项目,重跑,无效 DerivedData删除,重跑,无效 删除钥匙串重复证书,重跑,无效...

  • Android studio 清除无效资源,无效引用,无效代码

    删除无效资源删除无效资源 @源地址:http://blog.csdn.net/byszy/article/deta...

网友评论

      本文标题:301. 删除无效的括号

      本文链接:https://www.haomeiwen.com/subject/eeiwwltx.html