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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
本题主要是回溯法,能想到这里本题就迎刃而解了。话不多说直接上程序。
public class Solution {
public List<String> generateParenthesis(int n) {
if(n==0)return null;
ArrayList<String> result=new ArrayList<>();
getS(new StringBuilder(), 0, n, n, result);
return result;
}
public void getS(StringBuilder sBuilder,int sum,int a,int b,ArrayList<String> result){
if(a==0&&b==0){
result.add(sBuilder.toString());
}
for(int i=0;i<2;i++){
if(i==0&&a>0){
getS(sBuilder.append('('),sum+1,a-1,b,result);
sBuilder.setLength(sBuilder.length()-1);
}
if(i==1&&sum>0&&b>0){
getS(sBuilder.append(')'), sum-1, a, b-1,result);
sBuilder.setLength(sBuilder.length()-1);
}
}
}
}