Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, February 23, 2021

Generate All Possible Parentheses


Problem : 

Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses.  

Code :

 public List<String> AllParenthesis(int n)
    {
        List<String> result = new ArrayList<String>();
        generateParenthesis(n, result, n, "");
        return result;
    }
    
    public void generateParenthesis(int leftRemaining,
            List<String> result, int rightRemaining, String res)  {
        if(leftRemaining <= 0 && rightRemaining <=0) {
        result.add(res);
        return;
        }
        if(leftRemaining < rightRemaining) {
            generateParenthesis(leftRemaining, result, rightRemaining-1, res.concat(")"));
        }
        if(leftRemaining>0) {
            generateParenthesis(leftRemaining-1, result, rightRemaining, res.concat("("));
        }
    }

0 Comments:

Post a Comment

Stats