How to find all the different combinations of opening and closing brackets from the given number k using C#?

Finding all valid combinations of opening and closing brackets for a given number k is a classic backtracking problem in computer science. This problem generates all possible arrangements of k pairs of brackets where each opening bracket has a corresponding closing bracket in the correct order.

The solution uses a recursive backtracking approach that builds valid bracket combinations by placing opening brackets when available and closing brackets only when they don't exceed the number of opening brackets already placed.

Algorithm Overview

The backtracking algorithm follows these key rules −

  • Add an opening bracket if we haven't used all k opening brackets

  • Add a closing bracket only if it doesn't exceed the number of opening brackets

  • When we have k closing brackets, we have a valid combination

Bracket Generation Tree (k=2) "" { {{ {} {{}} {}{} Legend: Add { Add }

Syntax

The recursive function signature for bracket generation −

private static void GenerateBrackets(char[] arr, int index, int k, 
                                   int openCount, int closeCount)

Using Backtracking Algorithm

Example

using System;
using System.Collections.Generic;
using System.Text;

namespace BracketGeneration {
    public class BracketGenerator {
        public void GenerateAllBrackets(int k) {
            char[] arr = new char[2 * k];
            FindValidSequences(arr, 0, k, 0, 0);
        }
        
        private static void FindValidSequences(char[] arr, int index, int k, 
                                             int openBracket, int closeBracket) {
            if (closeBracket == k) {
                StringBuilder result = new StringBuilder();
                for (int i = 0; i < arr.Length; i++) {
                    result.Append(arr[i]);
                }
                Console.WriteLine(result.ToString());
                return;
            }
            
            // Add closing bracket if we have more open than close brackets
            if (openBracket > closeBracket) {
                arr[index] = '}';
                FindValidSequences(arr, index + 1, k, openBracket, closeBracket + 1);
            }
            
            // Add opening bracket if we haven't used all k opening brackets
            if (openBracket < k) {
                arr[index] = '{';
                FindValidSequences(arr, index + 1, k, openBracket + 1, closeBracket);
            }
        }
    }
    
    class Program {
        static void Main(string[] args) {
            BracketGenerator generator = new BracketGenerator();
            Console.WriteLine("All valid bracket combinations for k = 2:");
            generator.GenerateAllBrackets(2);
            
            Console.WriteLine("\nAll valid bracket combinations for k = 3:");
            generator.GenerateAllBrackets(3);
        }
    }
}

The output of the above code is −

All valid bracket combinations for k = 2:
{}{}
{{}}

All valid bracket combinations for k = 3:
{}{}{}
{}{{}}
{}{{}
{{}}{}
{{{}}}

Using List to Store Results

Example

using System;
using System.Collections.Generic;

namespace BracketCombinations {
    public class BracketSolver {
        public static List<string> GenerateBrackets(int k) {
            List<string> result = new List<string>();
            GenerateHelper("", 0, 0, k, result);
            return result;
        }
        
        private static void GenerateHelper(string current, int open, int close, 
                                         int k, List<string> result) {
            if (current.Length == 2 * k) {
                result.Add(current);
                return;
            }
            
            if (open < k) {
                GenerateHelper(current + "{", open + 1, close, k, result);
            }
            
            if (close < open) {
                GenerateHelper(current + "}", open, close + 1, k, result);
            }
        }
    }
    
    class Program {
        static void Main(string[] args) {
            int k = 3;
            List<string> combinations = BracketSolver.GenerateBrackets(k);
            
            Console.WriteLine($"Total combinations for k = {k}: {combinations.Count}");
            foreach (string combination in combinations) {
                Console.WriteLine(combination);
            }
        }
    }
}

The output of the above code is −

Total combinations for k = 3: 5
{}{}{}
{}{{}}
{}{{}
{{}}{}
{{{}}}

Time and Space Complexity

Aspect Complexity Explanation
Time Complexity O(4^k / ?k) Catalan number based on valid bracket sequences
Space Complexity O(k) Recursion depth and temporary array storage
Total Combinations C(k) = (2k)! / ((k+1)! * k!) kth Catalan number

Conclusion

Generating valid bracket combinations using backtracking efficiently explores all possibilities while maintaining the constraint that closing brackets never exceed opening brackets. The algorithm has applications in compiler design, expression parsing, and combinatorial mathematics, with time complexity following the Catalan number sequence.

Updated on: 2026-03-17T07:04:36+05:30

473 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements