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 ).

Example 1:

Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:

Input: "(a)())()"
Output: ["(a)()()", "(a())()"]
Example 3:

Input: ")("
Output: [""]

class Solution { public List<String> removeInvalidParentheses(String s) { Set<String> visited = new HashSet<>(); List<String> res = new ArrayList<>(); List<String> current = new ArrayList<>(); List<String> next; boolean reached = false; current.add(s); while(!current.isEmpty()){ next = new ArrayList<>(); for(String prv : current){ visited.add(prv); //if valid if(isValid(prv)){ reached = true; res.add(prv); } //not valid if(!reached){ for(int i=0; i<prv.length(); i++){ char tmp = prv.charAt(i); if(tmp == '(' || tmp == ')'){ String newString = prv.substring(0,i)+ prv.substring(i+1); if(!visited.contains(newString)){ next.add(newString); visited.add(newString); } } } } } if(reached){ break; } current = next; } return res; } private boolean isValid(String s){ Stack<Character> stack = new Stack<>(); for(int i=0; i<s.length(); i++){ char c = s.charAt(i); if(c == '('){ stack.push(c); } else if (c == ')'){ if(stack.isEmpty()){ return false; } else{ stack.pop(); } } } return stack.isEmpty(); } }

  

看到parenthese的问题,第一反应是用栈。这题要求minimum number,所以想到用BFS遍历解空间树。

思路为:

层次依次为删除0个元素,1个元素,2个元素。。。

层次遍历所有的可能。如果有一种可能是valid,那么不再遍历下面的层。

转载于:https://www.cnblogs.com/incrediblechangshuo/p/9252081.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值