Given n pairs of parentheses, write a function to generate all combinations of well-formed parenth
eses.
For example, given n = 3, a solution set is:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]參考思路:http://blog.csdn.net/u012501459/article/details/46787097
如果這道題是求上面括號的組合有多少種方式,那麼這是一道卡塔蘭數的題目,最開始就陷入到這裏了,按照卡塔蘭數的思路找尋遞歸關係式,怎麼也尋找不到,但這道題好像是另一類問題的一個標準模板,就是求解卡塔蘭數的具體組合是什麼樣的,這又是一種通用的解法。
對於這道題,第一個肯定是’(‘,接下來即可以是’(‘也可以是’)’,只需要滿足下面三條規則:
left:表示剩餘左括號的數目
right:表示剩餘右括號的數目
滿足的條件如下:
- 當left=0&&right=0時表示找到一條路徑
- 當left!=0時可以向左子樹伸展
- 當right!=0&&left< right時可以向右子樹伸展
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if(n == 0) return result;
int left = n;
int right = n;
String path = "";
findRes(n,n,result,path);
return result;
}
private void findRes(int left, int right,List<String> result, String path){
if(left == 0 && right == 0){
result.add(path);
return;
}
if(left != 0) findRes(left-1, right, result, path+'(');
if(right != 0 && left < right) findRes(left, right-1, result, path+')');
}
}