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);
}

posted on 2017-02-26 21:11  蒋闯  阅读(209)  评论(0编辑  收藏  举报