Generate Parentheses
题目
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
题目描述
输入括号的组数,返回合法括号组合
思路
当是组合数和所有可能的问题时,应当要想到递归。
下图是以输入3为例子的递归过程。
AC代码
public class Solution {
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
generate(0,0,"",n);
return result;
}
private void generate(int left, int right, String s, int n) {
if(right == n){
result.add(s);
}
else{
if(left < n)
{
generate(left + 1, right, s+"(", n);
}
if(right < left)
{
generate(left, right + 1, s+")", n);
}
}
}
}