Leetcode 301. Remove Invalid Parentheses

10 篇文章 0 订阅
3 篇文章 0 订阅


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())()"]
")(" -> [""]

Credits:
Analysis: this question is quite similar to all the Parentheses question. we need to make sure that the left ( is more than ), then if the number of the left ( is equal to the number of the right one ), there is a valid parentheses. then we just compare is to the maxValue.

1 This problem has a trick that how to delete the duplicates. this is quite common in backtracking

if(i != start && s.charAt(i)== s.charAt(i - 1))
          continue;

2 also consider the "", when the input string is "", we need to return a "" in the result

code 

public class Solution {
    int maxNum = 0;
    public List<String> removeInvalidParentheses(String s) {
      int left = 0;
      int right = 0;
      
      List<String> resultList = new ArrayList<String>();
      resultList.add("");
      int length = s.length();
      if(length == 0){
        return resultList;
      }
      int start = 0; //start is to record the begining bit to visit the String
      dfs( s, "", start, left, right,resultList,0);
      return resultList;
    }
    public void dfs(String s, String result, int start, int left, int right,List<String> resultList, int number){
      if(left == right && number != 0){
        if(number > maxNum){
          maxNum = number;
          resultList.clear();
          resultList.add(result);
        }
        else if(number == maxNum){
          resultList.add(result);
        }
      }
      int length = s.length();
      if(start >= length)
        return;
      for(int i = start; i < length; i++){
        if(i != start && s.charAt(i)== s.charAt(i - 1))
          continue;
        if(s.charAt(i) == '(')
          dfs(s,result + "(", i + 1, left + 1, right,resultList,number + 1);
        else if(s.charAt(i) == ')' && left > right)
          dfs(s,result + ")", i + 1, left, right + 1,resultList,number + 1);
        else if(s.charAt(i) != '(' && s.charAt(i) != ')')
          dfs(s,result + s.charAt(i),i + 1,left,right,resultList, number + 1);
      }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值