Generate All Parentheses  [Two Solutions]

Generate All Parentheses [Two Solutions]

·

1 min read

Problem Link - https://leetcode.com/problems/generate-parentheses/ and https://www.interviewbit.com/problems/generate-all-parentheses-ii/

Method 1: Iterative solution using BFS

class Solution {
    public List<String> generateParenthesis(int n) {
        LinkedList<String> allComb = new LinkedList<String>();
        allComb.add("");
// Main for loop to travese the tree BFS wise
        for(int i=1; i<=n; i++) {
            int j = 0;
            int queueLen = allComb.size();
// while loop to get the length of the nodes at each level
            while(j<queueLen) {
                String t = allComb.remove();
                int k = 0;
// Now we are adding a "()" for every index of the strings already in the queue
                while(k<i) {
                    StringBuffer newString = new StringBuffer(t);
                    newString.insert(k, "()");
                    if(!allComb.contains(newString.toString()))
                        allComb.add(newString.toString());
                    k++;
                }
                j++;
            }            
        }
        return allComb;       
    }
}

Method 2 - Using recursion

public class Solution {

    ArrayList<String> list;
    //HashSet<String> hset;
    public ArrayList<String> generateParenthesis(int A) {

        list = new ArrayList<>();
        helper(A, A, "", A+A);
        return list;

    }

    private void helper(int open, int close, String str, int len) {
        if(str.length()==len) {
            list.add(str);
            return;
        }

        if(open!=0) {
            String op = str + "(";
            helper(open-1, close, op, len);
        }

        if(close>open) {
            String op2 = str + ")";
            helper(open, close-1, op2, len);
            return;
        }
    } 
}

For time complexity read - https://leetcode.com/problems/generate-parentheses/editorial/