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时,剩下全部。不过,每一个方法的调用都会产生一个栈帧,每执行一个方法就会出现压栈操作,所以采用递归的时候产生的栈帧比较多,递归就会影响到内存,非常消耗内存。当左括号数大于右括号数时可以加左或者右括号,否则只能加左括号,当左括号数达到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);
    }

  • 相关阅读:
    业务对象(BO)设计
    业务对象和BAPI
    LSMW应用
    BDC、CATT批量数据维护
    ABAP RFC远程调用
    LIST动态表格画线(动态列)
    ALV详解:OO SALV
    ALV详解:OO ALV
    ALV详解:Function ALV(二)
    ALV详解:Function ALV(一)
  • 原文地址:https://www.cnblogs.com/huaiyinxiaojiang/p/6445914.html
Copyright © 2011-2022 走看看