zoukankan      html  css  js  c++  java
  • [Algo] 66. All Valid Permutations Of Parentheses I

    Given N pairs of parentheses “()”, return a list with all the valid permutations.

    Assumptions

    • N > 0

    Examples

    • N = 1, all valid permutations are ["()"]
    • N = 3, all valid permutations are ["((()))", "(()())", "(())()", "()(())", "()()()"]
    public class Solution {
      public List<String> validParentheses(int n) {
        // Write your solution here
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        helper(res, n, n, sb);
        return res;
      }
    
      private void helper(List<String> res, int left, int right, StringBuilder sb) {
        if (left == 0 && right == 0) {
          res.add(sb.toString());
          return;
        }
        if (left > 0) {
          sb.append("(");
          helper(res, left - 1, right, sb);
          sb.deleteCharAt(sb.length() - 1);
        }
        if (right > left) {
          sb.append(")");
          helper(res, left, right - 1, sb);
          sb.deleteCharAt(sb.length() - 1);
        }
      }
    }
  • 相关阅读:
    Tomcat December 31,2019
    XML
    Java
    mysql8.0.16安装(补) September 24,2019
    乱码中的编码和解码
    idea优化
    新版web.xml
    重定向和请求转发
    web下载文件设置的头信息
    响应状态码
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12316007.html
Copyright © 2011-2022 走看看