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: "((()))", "(()())", "(())()", "()(())", "()()()"

时间:2023-03-09 00:39:01
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);
}