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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题意:求给定n对原括号的组合可能数
解题思路:卡特兰数
代码:
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<String>();
generate(result, "", 0, 0, n);
return result;
}
private void generate(List<String> result, String str, int left, int right, int n){
if(left == n){
for(int i = 0; i < n - right; i++){
str += ")";
}
result.add(str);
return;
}
generate(result, str + "(", left + 1, right, n);
if(left > right){
generate(result, str + ")", left, right + 1, n);
}
}
}