301. Remove Invalid Parentheses去除不符合匹配规则的括号

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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]

Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]

Example 3:

Input: ")("
Output: [""]

思路:
本来想着append,偶尔一个skip??可是DFS里没有skip这一说,解决措施应该是多用几个DFS公式


没想到的是:L R形容的是多余出来的半边括号。不用的话,跳过去了,这个L没用。L - 1

加了个i当参数,因为需要控制退出的情况

可能是字母,所以就是append c

java里没有exit啊,都是return ;啊,醉了

class Solution {
    public List<String> removeInvalidParentheses(String s) {
        List<String> results = new ArrayList<>();
        int left = 0, right = 0, open = 0;
        int n = s.length();
        Set<String> set = new HashSet<String>();
        
        //cc
        if (s.length() < 0)
            return results;
        
        //统计L R的数量
        for (int i = 0; i < n; i++) {
            if (s.charAt(i) == '(')
                left++;
            else if (s.charAt(i) == ')')
                if (left > 0)
                    left--;
                else right++;
        }
        
        //dfs
        dfs(s, 0, left, right, 0, new StringBuilder(), set);
        
        //return
        return new ArrayList<String>(set);
    }
    
    public void dfs(String s, int i, int left, int right, int open, 
                    StringBuilder sb,
                    Set<String> set) {
        //这里有个cc,因为可能有边缘的情况
        if (left < 0 || right < 0 || open < 0)
            return;
        
        //exit
        if (i == s.length()) {
            if (left == 0 && right == 0 && open == 0)
                set.add(sb.toString());
                return;
        }
        
        //定义字符串的每一位
        char c = s.charAt(i);
        int len = sb.length();
        
        //分开进行DFS
        if (c == '(') {
            //不用
            dfs(s, i + 1, left - 1, right, open, sb, set);
            //用左括号
            dfs(s, i + 1, left, right, open + 1, sb.append(c), set);    
        }else if (c == ')') {
            //不用
            dfs(s, i + 1, left, right - 1, open, sb, set);
            //用右括号
            dfs(s, i + 1, left, right, open - 1, sb.append(c), set);
        }else {
            dfs(s, i + 1, left, right, open, sb.append(c), set);
        }
        
        //调整sb的长度
        sb.setLength(len);
    }
}
View Code



原文地址:https://www.cnblogs.com/immiao0319/p/13389922.html