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:
"((()))", "(()())", "(())()", "()(())", "()()()"
注意:string类的添加用 + “xxx”来添加,删除用substring(index1,index2)来删除。
StringBuffer类添加用append,删除用delete(int start, int end)或deleteCharAt(index)。
写在递归的形参中的无需再删除,每次返回的时候就自动去掉了。
Source
public class Solution {
public List<String> generateParenthesis(int n) {
List<String> st = new ArrayList<String>();
String a = new String();
if(n == 0) return st;
dfs(n, n, st, a);
return st;
}
public void dfs(int left, int right, List<String> st, String a){
if(left > right) //遍历先走了right ******
return ;
if(left == 0 && right == 0){
st.add(new String(a));
return ;
}
if(left > 0){
dfs(left - 1, right, st, a + "("); // a +"("写在递归里,相当于在递归语句前加上括号在递归语句后删除括号
}
if(right > 0){
dfs(left, right - 1, st, a + ")");
}
}
}
Test
public static void main(String[] args){
int n = 3;
System.out.println(new Solution().generateParenthesis(n));
}