Leetcode: Generate Parentheses
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: "((()))", "(()())", "(())()", "()(())", "()()()"
又是把所有满足条件的结果存到一个ArrayList里面, 之前也有类似的如Letter combination of a Phone Number这道题。这种类型的题其实形成了一个套路,套路就是,recursion参数包括最终结果的集合(ArrayList),input(String),递归层次level(int),某一条具体的路径Path
Code Ganker的做法,高手的代码就是简洁啊
1 public ArrayList<String> generateParenthesis(int n) { 2 ArrayList<String> res = new ArrayList<String>(); 3 if(n<=0) 4 return res; 5 helper(n,n,new String(),res); 6 return res; 7 } 8 private void helper(int l, int r, String item, ArrayList<String> res) 9 { 10 if(r<l) 11 return; 12 if(l==0 && r==0) 13 { 14 res.add(item); 15 } 16 if(l>0) 17 helper(l-1,r,item+"(",res); 18 if(r>0) 19 helper(l,r-1,item+")",res); 20 }