- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
{}{} {{}}
Advertisements