Very Concise and Clear Java Solution Beats 97%..


  • 1
    S

    List<String> ans=new ArrayList<String>();
    String open="(";
    String closed=")";
    public List<String> generateParenthesis(int n)
    {
    //The length of the string will be twice the input size.
    permutations("",0,0,2*n);
    return ans;
    }
    public void permutations(String st,int x,int y,int n)
    {
    //x: number of open brackets.
    //y: number of closed brackets.
    if(st.length()==n) { ans.add(st); return; }
    if(x<n/2) permutations(st+open,x+1,y,n);
    if(x==n/2 || x>y)permutations(st+closed,x,y+1,n);

    }

  • 0
    S

    @svcharan94 Wow!! This is an amazing solution. Thanks a lot.


Log in to reply
 

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