题目:(Backtrancing)
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
题解:
比较特殊的一条backingtrancing,其实也就是和我们的套路略有点出入
public class Solution { public ArrayList<String> generateParenthesis(int n) { ArrayList<String> list =new ArrayList<String>(); generate(list,"",0,0,n); return list; } public void generate(ArrayList<String> list,String res,int leftNum,int rightNum,int n){ //防错误的右边括号出现 if(leftNum<rightNum) return ; if(leftNum==n&&rightNum==n){ list.add(res); return ; } if(leftNum==n){ generate(list,res+")",leftNum,rightNum+1,n); return ; } generate(list,res+"(",leftNum+1,rightNum,n); generate(list,res+")",leftNum,rightNum+1,n); } }