1 题目
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
2 解法
思路:递归
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> lst = new ArrayList<String>();
String s = "";
recursive(lst, n, n, s);
return lst;
}
public void recursive(List<String>lst, int left, int right, String s) {
if(left == 0 && right == 0){
lst.add(s);
}
if(left > 0){
recursive(lst, left - 1, right, s+'(');
}
if(left < right){
recursive(lst, left, right - 1, s+')');
}
}
}