[LeetCode] 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 ).

Examples:

“()())()” -> [“()()()”, “(())()”]
“(a)())()” -> [“(a)()()”, “(a())()”]
“)(” -> [“”]

解题思路

括号总是成对出现的,因此我们只需要记录尚未匹配的
每次循环时有如下三种情况:

  • (, 保留或者不保留。
  • ), 如果我们有未匹配的,则有两种选择;否则,只能不保留。
  • 保留其他字符。

因为我们要移除数量最少的括号,我们应该得到最大的匹配()数量,注意下面两行的顺序。

dfs(str.substring(1), subRes + '(', countLeft + 1, maxLeft + 1);
dfs(str.substring(1), subRes, countLeft, maxLeft);

它可以保证最长的结果出现在比它较短的结果前面。

实现代码

Java:

// Runtime: 216 ms
public class Solution {
    private List<String> res = new ArrayList<String>();
    private int max = 0;
    public List<String> removeInvalidParentheses(String s) {
        dfs(s, "", 0, 0);
        if (res.size() == 0) {
            res.add("");
        }

        return res;
    }

    private void dfs(String str, String subRes, int countLeft, int maxLeft) {
        if (str.length() == 0) {
            if (countLeft == 0 && subRes.length() != 0) {
                if (maxLeft > max) {
                    max = maxLeft;
                }
                if (max == maxLeft && !res.contains(subRes)) {
                    res.add(subRes.toString());
                }
            }
            return;
        }

        if (str.charAt(0) == '(') {
            dfs(str.substring(1), subRes.concat("("), countLeft + 1, maxLeft + 1);
            dfs(str.substring(1), subRes, countLeft, maxLeft);
        } else if (str.charAt(0) == ')') {
            if (countLeft > 0) {
                dfs(str.substring(1), subRes.concat(")"), countLeft - 1, maxLeft);
            }
            dfs(str.substring(1), subRes, countLeft, maxLeft);
        } else {
            dfs(str.substring(1), subRes.concat(String.valueOf(str.charAt(0))), countLeft, maxLeft);
        }
    }
}
时间: 2024-10-31 23:32:23

[LeetCode] Remove Invalid Parentheses的相关文章

leetcode 22 Generate Parentheses关于C++ string的问题

问题描述 leetcode 22 Generate Parentheses关于C++ string的问题 /* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())

[LeetCode] Remove Comments 移除注释

Given a C++ program, remove comments from it. The program source is an array where source[i] is the i-th line of the source code. This represents the result of splitting the original source code string by the newline character \n. In C++, there are t

[LeetCode]22.Generate Parentheses

[题目] Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" [分

[LeetCode] 20.Valid Parentheses

[题目] Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]

leetcode 20 Valid Parentheses 括号匹配

Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]"

[LeetCode] Remove Linked List Elements

Remove all elements from a linked list of integers that have value val. Example Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6 Return: 1 –> 2 –> 3 –> 4 –> 5 解题思路 定义两个指针pre和cur,如果cur的值为val,则删除该结点.需要注意的情况有两种:①需要删除头结点:②链表为空. 实现

LeetCode 22 Generate Parentheses(生成括号)

翻译 给定一个括号序列,写一个函数用于生成正确形式的括号组合. 例如,给定n = 3,一个解决方案集是: "((()))", "(()())", "(())()", "()(())", "()()()" 原文 Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes

[LeetCode] Remove Duplicates from Sorted List - 链表问题

题目概述:Given a sorted linked list, delete all duplicates such that each element appear only once.For example,Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. 题目解析:这是一道非常简单的链表题目,题意是删除单链表(已排序)中的重复数字,只需一次判断前后两个结点数字是否相

LeetCode 20 Valid Parentheses(有效的括号)

翻译 给定一个只包含'(', ')', '{', '}', '[' 和']'的字符串,判断这个输入的字符串是否是有效的. 括号必须在正确的形式下闭合,"()" 和"()[]{}" 是有效的,但是 "(]" 和"([)]" 则不是. 原文 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the