zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Remove Invalid Parentheses

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

    Examples:

    "()())()" -> ["()()()", "(())()"]
    "(a)())()" -> ["(a)()()", "(a())()"]
    ")(" -> [""]
    https://leetcode.com/problems/remove-invalid-parentheses/
     
     
     
     

     
     
     
    ( 和 )总是成对出现的,出现在 ( 之前的 ) 没有意义。
    开变量countLeft记录还没匹配的 ( 的次数。
     
    每轮循环三种情况:
    1. (, 可以选择拿或不拿;
    2. ), 如果有没匹配的 ( ,可以选择拿或不拿,否则只能不拿;
    3. 其他字母直接拿。
     
    因为要移除最少的括号,开变量maxLeft记录最多有几对括号,即最多出现过几个匹配成功的 (。
    注意到这两句话的顺序:

    dfs(str.substring(1), subRes + '(', countLeft + 1, maxLeft + 1);
    dfs(str.substring(1), subRes, countLeft, maxLeft);

    保证了匹配括号多的结果一定会先出现在结果数组中,不会遗漏结果。

    https://leetcode.com/discuss/68272/straight-forward-solution-with-explanation

     1 /**
     2  * @param {string} s
     3  * @return {string[]}
     4  */
     5 var removeInvalidParentheses = function(s) {
     6     var res = [], max = 0;
     7     dfs(s, "", 0, 0);
     8     return res.length !== 0 ? res : [""];
     9 
    10     function dfs(str, subRes, countLeft, maxLeft){
    11         if(str === ""){
    12             if(countLeft === 0 && subRes !== ""){
    13                 if(maxLeft > max)
    14                     max = maxLeft;
    15                 if(max === maxLeft && res.indexOf(subRes) === -1)
    16                     res.push(subRes);
    17             }
    18             return;
    19         }
    20         if(str[0] === '('){
    21             dfs(str.substring(1), subRes + '(', countLeft + 1, maxLeft + 1);
    22             dfs(str.substring(1), subRes, countLeft, maxLeft);
    23         }else if(str[0] === ')'){
    24             if(countLeft > 0)
    25                 dfs(str.substring(1), subRes + ')', countLeft - 1, maxLeft);
    26             dfs(str.substring(1), subRes, countLeft, maxLeft);
    27         }else{
    28             dfs(str.substring(1), subRes + str[0], countLeft, maxLeft);
    29         }
    30     }
    31 };
     
     
  • 相关阅读:
    软件工程实践总结作业
    软工实践 产品个人分析
    软工交接情况
    结队第二次作业——WordCount进阶需求
    团队展示(团队)
    软工第一次结对
    软工实践第二次作业
    selenium_04_课堂笔记
    selenium_05_课堂笔记
    selenium_06_课堂笔记
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4946376.html
Copyright © 2011-2022 走看看