Generate Parentheses - LeetCode
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
思路:标准的递归题
犯的错误:
Line16 忘记加上判断条件会导致无限循环
1 public class Solution { 2 public ArrayList<String> generateParenthesis(int n) { 3 ArrayList<String> res= new ArrayList<String>(); 4 String str=""; 5 generateParanthesis(n,0,0,str,res); 6 return res; 7 } 8 9 public void generateParanthesis(int n, int l, int r, String str, ArrayList<String> res){ 10 if(r>l){ 11 return; 12 } 13 if(str.length()==2*n){ 14 res.add(str); 15 } 16 if(l<=n&&r<=n){ 17 if(r==l){ 18 generateParanthesis(n,l+1,r,str+"(",res); 19 }else{ 20 if(l<n) 21 generateParanthesis(n,l+1,r,str+"(",res); 22 generateParanthesis(n,l,r+1,str+")",res); 23 } 24 } 25 } 26 }