Leetcode 301.删除无效的括号
删除无效的括号
删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果。
说明: 输入可能包含了除 ( 和 ) 以外的字符。
示例 1:
输入: "()())()"
输出: ["()()()", "(())()"]
示例 2:
输入: "(a)())()"
输出: ["(a)()()", "(a())()"]
示例 3:
输入: ")("
输出: [""]
Approach 1: Backtracking
Intuition
For this question, we are given an expression consisting of parentheses and there can be some misplaced or extra brackets in the expression that cause it to be invalid. An expression consisting of parentheses is considered valid only when every closing bracket has a corresponding opening bracket and vice versa.
This means if we start looking at each of the bracket from left to right, as soon as we encounter a closing bracket, there should be an unmatched opening bracket available to match it. Otherwise the expression would become invalid. The expression can also become invalid if the number of opening parentheses i.e. ( are more than the number of closing parentheses i.e. ).
Let us look at an invalid expression and all the possible valid expressions that can be formed from it by removing some of the brackets. There is no restriction on which parentheses we can remove. We simply have to make the expression valid.
The only condition is that we should be removing the minimum number of brackets to make an invalid expression, valid. If this condition was not present, we could potentially remove most of the brackets and come down to say 2 brackets in the end which form () and that would be a valid expression.
An important thing to observe in the above diagram is that there are multiple ways of reaching the same solution i.e. say the optimal number of parentheses to be removed to make the original expression valid is K. We can remove multiple different sets of K brackets that will eventually give us the same final expression. But, each valid expression should be recorded only once. We have to take care of this in our solution. Note that there are other possible ways of reaching one of the two valid expressions shown above. We have simply shown 3 ways each for the two valid expressions.
Coming back to our problem, the question that now arises is, how to decide which of the parentheses to remove?
Since we don't know which of the brackets can possibly be removed, we try out all the options!
For every bracket we have two choices:
- Either it can be considered a part of the final expression OR
- It can be ignored i.e. we can delete it from our final expression.
Such kind of problems where we have multiple options and we have no strategy or metric of deciding greedily which option to take, we try out all of the options and see which ones lead to an answer. These type of problems are perfect candidates for the programming paradigm, Recursion.
Algorithm
- Initialize an array that will store all of our valid expressions finally.
- Start with the leftmost bracket in the given sequence and proceed right in the recursion.
- The state of recursion is defined by the index which we are currently processing in the original expression. Let this index be represented by the character i. Also, we have two different variables left_count and right_count that represent the number of left and right parentheses we have added to our expression till now. These are the parentheses that were considered.
- If the current character i.e. S[i] (considering S is the expression string) is neither a closing or an opening parenthesis, then we simply add this character to our final solution string for the current recursion.
- However, if the current character is either of the two brackets i.e. S[i] == '(' or S[i] == ')', then we have two options. We can either discard this character by marking it an invalid character or we can consider this bracket to be a part of the final expression.
- When all of the parentheses in the original expression have been processed, we simply check if the expression represented by expr i.e. the expression formed till now is valid one or not. The way we check if the final expression is valid or not is by looking at the values in left_count and right_count. For an expression to be valid left_count == right_count. If it is indeed valid, then it could be one of our possible solutions.
- Even though we have a valid expression, we also need to keep track of the number of removals we did to get this expression. This is done by another variable passed in recursion called rem_count.
- Once recursion finishes we check if the current value of rem_count is < the least number of steps we took to form a valid expression till now i.e. the global minima. If this is not the case, we don't record the new expression, else we record it.
One small optimization that we can do from an implementation perspective is introducing some sort of pruning in our algorithm. Right now we simply go till the very end i.e. process all of the parentheses and when we are done processing all of them, we check if the expression we have can be considered or not.
We have to wait till the very end to decide if the expression formed in recursion is a valid expression or not. Is there a way for us to cutoff from some of the recursion paths early on because they wouldn't lead to a solution? The answer to this is Yes! The optimization is based on the following idea.
For a left bracket encountered during recursion, if we decide to consider it, then it may or may not lead to an invalid final expression. It may lead to an invalid expression eventually if there are no matching closing bracket available afterwards. But, we don't know for sure if this will happen or not.
However, for a closing bracket, if we decide to keep it as a part of our final expression (remember for every bracket we have two options, either to keep it or to remove it and recurse further) and there is no corresponding opening bracket to match it in the expression till now, then it will definitely lead to an invalid expression no matter what we do afterwards.
e.g.
( ( ) ) )
In this case the third closing bracket will make the expression invalid. No matter what comes afterwards, this will give us an invalid expression and if such a thing happens, we shouldn't recurse further and simply prune the recursion tree.
That is why, in addition to having the index in the original string/expression which we are currently processing and the expression string formed till now, we also keep track of the number of left and right parentheses. Whenever we keep a left parenthesis in the expression, we increment its counter. For a right parenthesis, we check if right_count < left_count. If this is the case then only we consider that right parenthesis and recurse further. Otherwise we don't as we know it will make the expression invalid. This simple optimization saves a lot of runtime.
Now, let us look at the implementation for this algorithm.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; class Solution { private Set<String> validExpressions = new HashSet<String>();
private int minimumRemoved; private void reset() {
this.validExpressions.clear();
this.minimumRemoved = Integer.MAX_VALUE;
} private void recurse(
String s,
int index,
int leftCount,
int rightCount,
StringBuilder expression,
int removedCount) { // If we have reached the end of string.
if (index == s.length()) { // If the current expression is valid.
if (leftCount == rightCount) { // If the current count of removed parentheses is <= the current minimum count
if (removedCount <= this.minimumRemoved) { // Convert StringBuilder to a String. This is an expensive operation.
// So we only perform this when needed.
String possibleAnswer = expression.toString(); // If the current count beats the overall minimum we have till now
if (removedCount < this.minimumRemoved) {
this.validExpressions.clear();
this.minimumRemoved = removedCount;
}
this.validExpressions.add(possibleAnswer);
}
}
} else { char currentCharacter = s.charAt(index);
int length = expression.length(); // If the current character is neither an opening bracket nor a closing one,
// simply recurse further by adding it to the expression StringBuilder
if (currentCharacter != '(' && currentCharacter != ')') {
expression.append(currentCharacter);
this.recurse(s, index + 1, leftCount, rightCount, expression, removedCount);
expression.deleteCharAt(length);
} else { // Recursion where we delete the current character and move forward
this.recurse(s, index + 1, leftCount, rightCount, expression, removedCount + 1);
expression.append(currentCharacter); // If it's an opening parenthesis, consider it and recurse
if (currentCharacter == '(') {
this.recurse(s, index + 1, leftCount + 1, rightCount, expression, removedCount);
} else if (rightCount < leftCount) {
// For a closing parenthesis, only recurse if right < left
this.recurse(s, index + 1, leftCount, rightCount + 1, expression, removedCount);
} // Undoing the append operation for other recursions.
expression.deleteCharAt(length);
}
}
} public List<String> removeInvalidParentheses(String s) { this.reset();
this.recurse(s, 0, 0, 0, new StringBuilder(), 0);
return new ArrayList(this.validExpressions);
}
}
Leetcode 301.删除无效的括号的更多相关文章
- Java实现 LeetCode 301 删除无效的括号
301. 删除无效的括号 删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果. 说明: 输入可能包含了除 ( 和 ) 以外的字符. 示例 1: 输入: "()())()&quo ...
- [LeetCode]301. 删除无效的括号(DFS)
题目 题解 step1. 遍历一遍,维护left.right计数器,分别记录不合法的左括号.右括号数量. 判断不合法的方法? left维护未匹配左括号数量(增,减)(当left为0遇到右括号,则交由r ...
- Leetcode之深度优先搜索(DFS)专题-301. 删除无效的括号(Remove Invalid Parentheses)
Leetcode之深度优先搜索(DFS)专题-301. 删除无效的括号(Remove Invalid Parentheses) 删除最小数量的无效括号,使得输入的字符串有效,返回所有可能的结果. 说明 ...
- 301 Remove Invalid Parentheses 删除无效的括号
删除最小数目的无效括号,使输入的字符串有效,返回所有可能的结果.注意: 输入可能包含了除 ( 和 ) 以外的元素.示例 :"()())()" -> ["()()() ...
- [Swift]LeetCode301. 删除无效的括号 | Remove Invalid Parentheses
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- [LeetCode] 301. Remove Invalid Parentheses 移除非法括号
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all ...
- [LeetCode] 20. Valid Parentheses 合法括号
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...
- 每日一道 LeetCode (6):有效的括号
每天 3 分钟,走上算法的逆袭之路. 前文合集 每日一道 LeetCode 前文合集 代码仓库 GitHub: https://github.com/meteor1993/LeetCode Gitee ...
- word中几个好用的宏代码(立方米上标、关闭样式自动更新、删除无效样式、表格加粗边框、宋体引号)
Sub 替换立方米() With Selection.Find .Text = "m3" .Replacement.Text = "mm3" .Forward ...
随机推荐
- 水题 Codeforces Round #303 (Div. 2) A. Toy Cars
题目传送门 /* 题意:5种情况对应对应第i或j辆车翻了没 水题:其实就看对角线的上半边就可以了,vis判断,可惜WA了一次 3: if both cars turned over during th ...
- bash 变量传递方法
###1.sh ##(该sh 目的是 将变量env传入env.sh, 同时让env.sh在当前事物生效,最后执行env.sh 定义的变量envs) export ENV=prepareecho ...
- pkill 和 pgrep总结
查看进程ID和方便kill进程 pgrep -d 指定分隔符 pgrep -d ' ' -u root 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 -u p ...
- hashTable 和 hashMap的区别
HashMap是Hashtable的轻量级实现(非线程安全的实现),他们都完成了Map接口,HashMap把Hashtable的contains方法去掉了,改成containsvalue和contai ...
- 合理设置apache的连接数及进程工作方式
网站在线人数增多,访问时很慢.初步认为是服务器资源不足了,但经反复测试,一旦连接上,不断点击同一个页面上不同的链接,都能迅速打开,这种现象就是说明apache最大连接数已经满了,新的访客只能排队等待有 ...
- AJPFX对选择和冒泡两种排序的理解
冒泡排序和直接选择排序都是排序中比较简单和容易实现的算法,先简单说说两者的区别:先以按照元素从小到大为:冒泡排序:将相邻元素两两比较,如果有比较大的,就把比较大的放在右边,这样的结果就是一轮排序完毕后 ...
- Spring源码:Spring IoC容器加载过程(1)
Spring源码版本:4.3.23.RELEASE 一.加载过程概览 Spring容器加载过程可以在org.springframework.context.support.AbstractApplic ...
- CF962D Merge Equals
思路: 不必每次都找最小的值进行合并,从前往后扫一遍的过程中能合并就一直合并. 实现: #include <bits/stdc++.h> using namespace std; type ...
- fetch和axios区别,proxy代理配置
1.今天使用fetch调用接口时使用console.log(res.data)始终是undefined,使用anxios请求则可以成功请求到数据,非常奇怪,于是查了一圈,才搞明白是我自以为了,哎,浪费 ...
- 分享一个开源的JavaScript统计图表库,40行代码实现专业统计图表
提升程序员工作效率的工具/技巧推荐系列 推荐一个功能强大的文件搜索工具SearchMyFiles 介绍一个好用的免费流程图和UML绘制软件-Diagram Designer 介绍Windows任务管理 ...