Leetcode Generate Parentheses problem solution in Java programming

In the Leetcode Generate Parentheses problem solution in Java programming Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Leetcode Generate Parentheses problem solution in Java programming

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList();
        StringBuilder currStr = new StringBuilder();
        int leftPars = n;
        int rightPars = n;
        dfs(leftPars, rightPars, currStr, result);
        return result;
        // T.C: O(n)
        // S.C: O(n)
    }
    
    public void dfs(int leftPars, int rightPars, StringBuilder currStr, List<String> result) {
        if (leftPars == 0 && rightPars == 0) {
            result.add(currStr.toString());
            return;
        }
        
        if (leftPars > 0) {
            currStr.append("(");
            dfs(leftPars - 1, rightPars, currStr, result);
            currStr.deleteCharAt(currStr.length() - 1);
        }
        
        if (rightPars > 0 && rightPars > leftPars) {
            currStr.append(")");
            dfs(leftPars, rightPars - 1, currStr, result);
            currStr.deleteCharAt(currStr.length() - 1);
        }
    }
}

Also read,

By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.

Leave a Reply

Your email address will not be published. Required fields are marked *