目录
- 题目描述:
 - 纯递归解法:
 - 递归 + 回溯:
 
题目描述:
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:[“((()))”,“(()())”,“(())()”,“()(())”,“()()()”]
示例 2:
输入:n = 1
输出:[“()”]
纯递归解法:
思路:
1. n对括号,每个括号由左右两个部分组成,那么转换一下就是由2n个部分组成
2.用暴力递归用左右括号将长度为2n的数组填满
3.检验生成的括号序列是否满足要求
左括号则加一,右括号则减一,若小于0则说明括号不匹配(即右括号,左括号),最后结果不为0说明结果也不匹配。
 
理论成立代码如下:
class Solution {
    public List<String> generateParenthesis(int n) {
           List final_result = new ArrayList<String>();
           get(new char [2*n], 0, final_result);
           return final_result;
    }
    
    public static void get(char a[], int index, List<String> result) {
    	if(index == a.length) {	
    		if(check(a)) result.add(new String(a));//重新粘贴一个a
    	}
    	else {
    	     a[index] = '(';
    	     get(a, index + 1, result);
    	     a[index] = ')';
    	     get(a, index + 1, result);
    	}
    }
    
    public static boolean check(char a[]) {
    	int balance = 0;
    	for(char b : a) {
    		if(b == '(') balance ++;
    		else balance --;
    		if(balance < 0) return false;
    	}
    	
    	return balance == 0;
    }
}
 
注意: 储存正确序列时一定要重新创建一个对象变量,因为list是指向型的。

递归 + 回溯:
对传入的左括号没有限制,右括号必须数量在小于左括号的前提下,试探添加。进而剪掉一些不符合要求的生成序列
代码:
class Solution {
    public List<String> generateParenthesis(int n) {
    	List final_result = new ArrayList<String>();
    	get(n, n,new String(), final_result);
    	return final_result;
    }
    
    public static void get(int l, int r, String s, List<String> result) {
    	if(l == 0 && r == 0) {
    	  result.add(s);
    	}
        if(l > 0) {
        	String s2 = new String(s);
        	get(l - 1, r, s + "(", result);
        }
        
        if(r > l) {
        	get(l, r - 1, s + ")", result);
        }
    }
}
 

注意由于String在传入函数时,会生成另一个新副本,所以在当次函数中未被修改



















