题目描述:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路解析:
- left代表左括号剩余的个数,right代表右括号剩余的个数
- 如果左括号大于右括号的个数,就结束了
- 如果都为0,就可以加入到ArrayList中
代码:
import java.util.*;
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> res = new ArrayList<String>();
if(n<0)
return res;
String item = new String();
helper(n,n,item,res);
return res;
}
public void helper(int left,int right,String item,ArrayList<String> res){
if(left>right)
return ;
if(left==0 && right==0){
res.add(new String(item));
return;
}
if(left>0){
helper(left-1,right,item+'(',res);
}
if(right>0)
helper(left,right-1,item+')',res);
}
}