- 给一个数字n,给出所有的n个左右括号组成的可用组合:
- 输入:2 输出:(()),()()
- 递归,左括号个数大于右括号可以继续增加,如果少于那么说明组合错误,停止递归,代码如下:
public class AddParen {
public ArrayList<String> genParens(int n){
ArrayList<String> res = new ArrayList<>();
char [] str = new char[n*2];
addParen(res, n, n, str, 0);
return res;
}
public void addParen(ArrayList<String> list, int leftRem, int rightRem, char [] str, int count){
if(count == str.length) {
list.add(String.valueOf(str));
}
if(leftRem > 0) {
str[count] = '(';
addParen(list, leftRem - 1, rightRem, str, count + 1);
}
if(rightRem > 0 && rightRem > leftRem) {
str[count] = ')';
addParen(list, leftRem, rightRem - 1, str, count + 1);
}
}
}