Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

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

Sharing is caring!

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

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]);
    }
}