【LeetCode】301.Remove Invalid Parentheses(hard)解题报告

【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日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值