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


Create a backtrack function that updates the current string if open brackets are less than n or close bracket are less than open bracket. When the length of current string becomes equal to 2*n, add it to the combination result array. It could be simply tracked by keeping the number of { } placed . We can start an opening bracket if we still have one left to place. And we can start a closing bracket if it would not exceed the number of opening brackets.

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class BackTracking{
      public void Brackets(){
         char[] arr = new char[4];
         FindSequence(arr, 0, 2, 0, 0);
      }
      private static void FindSequence(char[] arr, int index, int N, int openBracket, int closeBracket){
         if (closeBracket == N){
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < arr.Length; i++){
               s.Append(arr[i]);
            }
            Console.WriteLine(s);
            s = null;
               return;
         }
         else{
            if (openBracket > closeBracket){
               arr[index] = '}';
               FindSequence(arr, index + 1, N, openBracket, closeBracket + 1);
            }
            if (openBracket < N){
               arr[index] = '{';
               FindSequence(arr, index + 1, N, openBracket + 1, closeBracket);
            }
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         b.Brackets();
      }
   }
}

Output

{}{}
{{}}

Updated on: 27-Aug-2021

265 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements