leetcode笔记系列 22 括号生成

题目描述:给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

可采用递归的方法。
代码如下:

public List<String> generateParenthesis(int n) {
  List<String> result = new ArrayList<String>();
  char[] bracket = new char[n*2];
  bracket[0]='(';
  getBrackets(n, 1, 1, 0,bracket, result);
  return result;
}
public void getBrackets(int total, int index, int left, int right, char[] bracket, List<String> result) {
  if (index == 2 * total) {
    result.add(new String(bracket));
    return; 
  }

  if (left < total) {
    bracket[index] = '(';

    getBrackets(total, index + 1, left + 1, right, bracket, result);
  }

  if (right < total && left > right) {
    bracket[index] = ')';
    getBrackets(total, index + 1, left, right + 1, bracket, result);
  }

}

方法的参数解释:1.total-括号总对数;2.index-当前打印的括号所在位置;3.left-已打印的左括号个数;4.right-已打印的右括号个数;5.打印的结果。
判断过程:1.当前打印的位置,不能超过total*2(递归结束条件);2.left只要小于total,就可以继续打印左括号;3.rigth需要小于total和left时,才能打印右括号。
当打印了一个左括号之后,index+1,left+1.其余不变。打印右括号同理。

猜你喜欢

转载自www.cnblogs.com/albert-ygy/p/9259970.html