题目描述
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
思路分析
由题意,每个括号都要有开有比,所以,把括号分为开(left)闭(right)两组,开>0,则插入左括号,闭括号同理;开括号小于闭括号,则插入闭括号。
代码
public List<String> generateParenthesis(int n) {
List<String> list = new ArrayList<String>();
generate("", list, n, n);
return list;
}
public void generate(String str, List<String> list, int left, int right){
if (left > right) {
return;
}
if (left > 0) {
generate(str, list, left-1, right);
}
if (right > 0) {
generate(str, list, left, right-1);
}
if (left==0 && right==0) {
list.add(str);
return;
}
}
结果