LeetCode: Generate Parentheses

Anonymous
1 min readJun 19, 2021

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

Intuition: The simplest way to tackle this would be to generate all 2^(2n) strings containing ‘(’ and ‘)’, then validate each of this strings if they are valid or not. However this is not an optimal solution since time complexity would be O((2^(2n)) * n) and space complexity would also be O((2^(2n)) * n).

Optimal Solution(Backtracking): In this approach, we add ‘(’ and ‘)’ only when we know the sequence getting created will be valid. The code for the same is below:

class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList();

backtrack(res, n, new StringBuilder(), 0, 0);
return res;
}

public void backtrack(List<String> res, int n, StringBuilder curr, int open, int close) {
if(curr.length() == 2*n){
//valid string added to result
res.add(curr.toString());
return;
}

if(open < n) {
//since open paranthesis are still left
curr.append("(");
backtrack(res, n, curr, open+1, close);
curr.deleteCharAt(curr.length()-1);
}

if(close < open){
//since closing paranthesis are less
curr.append(")");
backtrack(res, n, curr, open, close+1);
curr.deleteCharAt(curr.length()-1);
}
}
}

--

--