n对括号的所有有效组合

编程入门 行业动态 更新时间:2024-10-26 07:36:01
本文介绍了n对括号的所有有效组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述
  • 我正在学习js ..
    • 我正在尝试编写一个简单的js程序..
    • 我要做的是打印n对括号的所有有效组合(正确打开和关闭)
    • 例如(),(()( )),(())
    • 我写的逻辑可以告诉我它是否正确
    • I am learning js now..
      • I am trying to write a simple js programme..
      • what I am trying to do is to print all valid combinations of n-pair of parenthesis(properly opened and closed)
      • eg (), (()()),(())
      • i have written the logic can you tell me whether its correct or not

      jsfiddle/e7mcp6xb/

      module.exports = Parentheses = (function() { var _isParenthesesMatch = function(str) { var parentheses = str.length; var rightParentheses = '('; var leftParentheses = ')'; var rightCount = 0; var leftCount = 0; for(i=0;i<=str.length;i++){ if(rightParentheses == str.charAt(i)) { rightCount++; } else if(leftParentheses == str.charAt(i)) { leftCount++; } } if(rightCount == leftCount){ return true; } else(rightCount != leftCount){ return false; } } }());

      推荐答案

      检查错误,但您可以轻松修复:在 for 循环的每一步中,左括号的数量不能小于结束数量:

      The check is wrong, but You can fix it easily: In each step of the for loop the number of opening parenthesis cannot be smaller than the number of closing ones:

      if (rightCount < leftCount) return false;

      整个函数应如下所示:

      function(str) { var rightParentheses = '('; var leftParentheses = ')'; var rightCount = 0; var leftCount = 0; for (var i = 0; i <= str.length; i++) { if (rightParentheses == str.charAt(i)) rightCount++; else if (leftParentheses == str.charAt(i)) leftCount++; if (rightCount < leftCount) return false; } return rightCount == leftCount; }

      如果您想生成所有有效字符串,可以使用此功能:

      If You'd like to generate all valid strings, you can use this function:

      function nPair(n) { if (n == 0) return [""]; var result = []; for (var i = 0; i < n; ++i) { var lefts = nPair(i); var rights = nPair(n - i - 1); for (var l = 0; l < lefts.length; ++l) for (var r = 0; r < rights.length; ++r) result.push("(" + lefts[l] + ")" + rights[r]); } return result; } // result of nPair(3): // ["()()()", "()(())", "(())()", "(()())", "((()))"]

更多推荐

n对括号的所有有效组合

本文发布于:2023-11-29 18:32:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647250.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   括号

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!