# Implement an algorithm to print all valid (e g , properly opened and closed) combinations of n-pairs of parentheses

**Problem Statement**

Implement an algorithm to print all valid (e g , properly opened and closed) combinations of n-pairs of parentheses

**Example**

Input: 3 (e g , 3 pairs of parentheses)

Output: ()()(), ()(()), (())(), ((()))

**Solution**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class PrintAllValidParens { static void solve(int l, int r, int i, char[] str) { if (l == 0 && r == 0) { System.out.println(new String(str)); } else { if (l > 0) { str[i] = '('; solve(l - 1, r, i + 1, str); } if (r > 0 && r > l) { str[i] = ')'; solve(l, r - 1, i + 1, str); } } } public static void main(String[] args) { solve(3, 3, 0, new char[6]); } } |