Categories: 23 DSA Patterns

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement:

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

Example 1: Input: n = 3 Output: [“((()))”,”(()())”,”(())()”,”()(())”,”()()()”]
Example 2: Input: n = 1 Output: [“()”]

Solution:

This problem can be solved using the concept of backtracking, Let’s see how to approach it.

Recursion Tree (Backtracking)

We have to write a function generate([], left, right, str=””, n)

[] -> Stores the result

left -> represents the opening bracket

right -> represents the closing bracket

str -> Stores each bracket in each iteration

n -> Input size

Step 1: Base condition of the recursion if(str. length() == 2*n) add balanced parenthesis string in result = [] and return.

Taking 2*n because for n = 1, str = “()” of size 2, n = 2, str = “(())” of size 4.

Step 2:

check condition (left < n) if it’s true then call function generate([], left + 1, right, str+”(“, n)

Step 3:

check condition (right < left) if it’s true then call function generate([], left, right + 1, str+”)”, n)

Step 4:

In the end, it will give the final result, which contains all combinations of balanced parenthesis.

All the above steps (1, 2, and 3) will repeat until they create all balanced parenthesis combinations.

Note: Try yourself, then look into the code.

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

    public void dfs(List<String> res, int left, int right, String s, int n) {

        if(s.length() == n*2) {

            res.add(s);
            return;
        }

        if(left < n) {

            dfs(res, left + 1, right, s + "(", n);
        }

        if(right < left) {

            dfs(res, left, right+1, s + ")", n);
        }
    }
}

Time Complexity: O(2^n) because of the recursive tree.

Space Complexity: O(1) because there is no extra space taking, only one List<String> which is required as output.

I hope you understand the approach to solving this problem.

Peace ✌️

Share
Published by
Hassan Raza

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

1 year ago