leetcode笔记系列 22 括号生成
题目描述:
给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
例如,给出 n = 3,生成结果为:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
可采用递归的方法。
代码如下:
1 public List<String> generateParenthesis(int n) { 2 List<String> result = new ArrayList<String>(); 3 char[] bracket = new char[n*2]; 4 bracket[0]='('; 5 getBrackets(n, 1, 1, 0,bracket, result); 6 return result; 7 } 8 public void getBrackets(int total, int index, int left, int right, char[] bracket, List<String> result) { 9 if (index == 2 * total) { 10 result.add(new String(bracket)); 11 return; 12 } 13 14 if (left < total) { 15 bracket[index] = '('; 16 17 getBrackets(total, index + 1, left + 1, right, bracket, result); 18 } 19 20 if (right < total && left > right) { 21 bracket[index] = ')'; 22 getBrackets(total, index + 1, left, right + 1, bracket, result); 23 } 24 25 }
方法的参数:1.total-括号总对数;2.index-当前打印的括号所在位置;3.left-已打印的左括号个数;4.right-已打印的右括号个数;5.打印的结果。
判断过程:1.当前打印的位置,不能超过total*2(递归结束条件);2.left只要小于total,就可以继续打印左括号;3.rigth需要小于total和left时,才能打印右括号。
当打印了一个左括号之后,index+1,left+1.其余不变。打印右括号同理。

浙公网安备 33010602011771号