【LeetCode】301.Remove Invalid Parentheses(hard)解题报告
题目地址:https://leetcode.com/problems/remove-invalid-parentheses/description/
题目描述:
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())()”]
“)(” -> [“”]看到括号可能想到用stack,此道题用的不是一般的backtracking。左括号必有括号多,则有可能以后变为合法。若有括号比左括号多,一定非法。return很重要,其中reverse很精髓。还可以使用BFS,以后添加。详解可见https://www.youtube.com/watch?v=5nAUGSC2ZGc&index=19&list=PLvyIyKZVcfAkZLa34w830wzUq7_qhdtBO
Solution:
//time:do not know
//space:O(n)
class Solution {
public List<String> removeInvalidParentheses(String s) {
List<String> res = new ArrayList<>();
helper(res,s,0,0,new char[]{'(',')'});
return res;
}
public void helper(List<String> res,String s,int last_i,int last_j,char[] pair){
for(int count=0 ,i=last_i;i<s.length();i++){
if(s.charAt(i) == pair[0]) count++;
if(s.charAt(i) == pair[1]) count--;
if(count>=0) continue;
for(int j=last_j;j<=i;j++){
if(s.charAt(j)==pair[1] && (j == last_j || s.charAt(j-1) != pair[1])){
helper(res,s.substring(0,j)+s.substring(j+1),i,j,pair);
}
}
return; //很重要,没有的话会有重复解
}
String reversed = new StringBuilder(s).reverse().toString();
if(pair[0]=='('){
helper(res,reversed,0,0,new char[]{')','('});
}else{
res.add(reversed);
}
}
}
Date:2018年1月16日