C# || How To Find All Combinations Of Well-Formed Brackets Using C#

Print Friendly, PDF & Email

The following is a program with functions which demonstrates how to find all combinations of well-formed brackets using C#.

The task is to write a function Brackets(int n) that prints all combinations of well-formed brackets from 1…n. For example, Brackets(3), the output would be:

(()) ()()
((())) (()()) (())() ()(()) ()()()

The number of possible combinations is the Catalan number of N pairs C(n).

1. Find All Well-Formed Brackets

The example below demonstrates the use of the ‘Brackets‘ function to find all the well-formed bracket combinations.

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

Pair: 1, Combination: ()
Pair: 2, Combination: (()), ()()
Pair: 3, Combination: ((())), (()()), (())(), ()(()), ()()()
Pair: 4, Combination: (((()))), ((()())), ((())()), ((()))(), (()(())), (()()()), (()())(), (())(()), (())()(), ()((())), ()(()()), ()(())(), ()()(()), ()()()()

Was this article helpful?
👍 YesNo

Leave a Reply