题目
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
代码
For 2, it should place one "()" and add another one insert it but none tail it,
'(' f(1) ')' f(0)
or add none insert it but tail it by another one,
'(' f(0) ')' f(1)
Thus for n, we can insert f(i) and tail f(j) and i+j=n-1,
'(' f(i) ')' f(j)
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
if (n == 0) {
result.add("");
} else {
for (int i = n - 1; i >= 0; i--) {
List<String> insertSub = generateParenthesis(i);
List<String> tailSub = generateParenthesis(n - 1 - i);
for (String insert : insertSub) {
for (String tail : tailSub) {
result.add("(" + insert + ")" + tail);
}
}
}
}
return result;
}
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/

本文介绍了一个递归算法,用于生成所有合法的n对括号组合。通过递归地在已有的括号序列中插入新的括号对,最终得到所有可能的合法组合。

被折叠的 条评论
为什么被折叠?



