zoukankan      html  css  js  c++  java
  • Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()"

    思路:采用递归树的思想,当左括号数大于右括号数时可以加左或者右括号,否则只能加左括号,当左括号数达到n时,剩下全部

    public static void main(String[] args){
      ArrayList<String> res = new ArrayList<String>();
      Scanner input = new Scanner(System.in);
      System.out.println("请输入n:");
      int n = input.nextInt();
      generate(res, "", 0, 0, n);
      System.out.println(res);
    }
    public static void generate(ArrayList<String> res, String tmp, int lhs, int rhs, int n){
      if(lhs == n){
        for(int i = 0; i < n - rhs; i++){
          tmp += ")";
        }
        res.add(tmp);
        return ;
      }
      generate(res, tmp + "(", lhs + 1, rhs, n);
      if(lhs > rhs)
        generate(res, tmp + ")", lhs, rhs + 1, n);
    }

  • 相关阅读:
    第二次编程作业总结
    structs get 方法乱码问题
    网址记录
    尸体解剖报告
    最后冲刺
    回答自己的提问——对自己最大的反馈
    构建之法13-17章读后感
    典型场景
    对其他各团队的评价
    用户调研
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6445913.html
Copyright © 2011-2022 走看看