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

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
Constraints:

Contents

In this approach, we are going to apply Backtracking technique, i.e. we are going to construct a decision tree with the valid rules and solve the problem recursively.

Valid Rules:

Let's look at an example with n=3, when we apply above rules, decision tree will look like this, at each level we will check with both possibilities of adding a left bracket '(' or a right bracket ')'. As you can see below, there are 5 valid parentheses can be drawn from n=3. decision tree with n=3

Implementation steps:
import java.util.ArrayList; import java.util.List; import java.util.Stack; import java.util.stream.Collectors; public class GenerateParentheses { static List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); helper(n, 0, 0, new Stack<>(), res); return res; } static void helper(int n, int openN, int closeN, Stack<Character> stack, List<String> result) { if(openN == closeN && openN == n) { result.add(stack.stream().map(String::valueOf).collect(Collectors.joining())); return; } if(openN < n) { stack.push('('); helper(n, openN+1, closeN, stack, result); stack.pop(); } if(closeN<openN) { stack.push(')'); helper(n, openN, closeN+1, stack, result); stack.pop(); } } public static void main(String[] args) { System.out.println(generateParenthesis(3)); } }
Complexity Analysis:

Time complexity: Above code runs in O(2n) since we are calling helper function recursively, with all possibilities.
Space complexity: O(n), since we are calling the helper function recursively, this is the memory used by memory stack.

Above implementations source code can be found at GitHub link for Java code