# Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

`class Solution {    public List<String> generateParenthesis(int n) {        List<String> output = new ArrayList<String>();        if(n == 0){            return output;        }        generateBrackets(0,0,output, "", n);        return output;    }    public void generateBrackets(int open, int close, List<String>       output, String str, int n){        if(close == n){            output.add(str);            return;        }        if(open<n){            str = str + "(";            open++;            generateBrackets(open, close, output, str, n);            str = str.substring(0, str.length()-1);            open--;        }        if(close<open){            str = str + ")";            close++;            generateBrackets(open, close, output, str, n);            str = str.substring(0, str.length()-1);            close--;        }    }}`

Recursion Graph below tells us that first we will fill all left brackets and while filling right brackets , we will check whether the count of left bracket is greater so that we can add right bracket in the tree.

Hope it will help someone to understand better how can we make problem simple by taking it as a tree.

--

--