My code is java .accept


  • 0
    X

    public class Solution {
    public static List<String> generateParenthesis(int n) {
    List<String> res=new ArrayList<String>();
    String tem="";
    generate(res,tem,0,0,n);
    return res;

    }
    public static void generate(List<String> res,String tem,int left,int right,int n)
    {

       if(left==n&&right==n)
    {
       res.add(tem);
       return;
    }
    if(left<right)
       return;
    if(left==n)
    {
      
       generate(res,tem+')',left,right+1,n);
       return;
    }
    generate(res,tem+'(',left+1,right,n);//计算左边的数目和右边的数目
    generate(res,tem+')',left,right+1,n);
    
    	
    }
    

    }


  • 0
    W

    Formatted the solution above:

       public class Solution {
        	public static List generateParenthesis(int n) {
        		List res = new ArrayList();
        		String tem = "";
        		generate(res, tem, 0, 0, n);
        		return res;
        
        	}
        
        	public static void generate(List res, String tem, int left, int right, int n) {
        
        		if (left == n && right == n) {
        			res.add(tem);
        			return;
        		}
        		if (left < right)
        			return;
        		if (left == n) {
        
        			generate(res, tem + ')', left, right + 1, n);
        			return;
        		}
        		generate(res, tem + '(', left + 1, right, n); // 计算左边的数目和右边的数目
        		generate(res, tem + ')', left, right + 1, n);
        
        	}
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.