当前位置:网站首页>5. bracket generation

5. bracket generation

2022-06-09 11:52:00 Yuan Sheng Xiao 196

subject :

Numbers  n  Represents the logarithm of the generated bracket , Please design a function , Used to be able to generate all possible and   Effective   Bracket combination .

Their thinking ( to flash back ):
        
Incoming numbers n Represents logarithm , This n The branching options that can be thought of as parentheses are from 0 To n,n As many as there are n+1 Secondary selection . Also make sure that the returned pair of parentheses is correct , Then the right parenthesis must be less than or equal to the number of left parentheses , Can continue to run , So if the right parenthesis is larger than the left parenthesis, you can return directly , There is no need to go any further , Only one parenthesis is added to the recursive function at a time , After the addition, it is handed over to the next recursive function for execution , If the left bracket equals the right bracket equals n You can put characters in the returned list to return

  Source code :

        public IList<string> GenerateParenthesis(int n)
        {
            // Define a table to store the correct string 
            IList<string> result = new List<string>();
            backTracking(n, result, 0, 0, "");
            return result;
        }

        private void backTracking(int n,IList<string> result,int left,int right,string str)
        {
            // If the right bracket is larger than the left bracket, return 
            if (right > left)
                return;

            // If the number of left parentheses is equal to the number of right parentheses is equal to n The number of indicates that the string is in compliance with the regulations , Just add him back List in 
            if(left == right && right == n)
            {
                result.Add(str);
                return;
            }

            // If the left bracket is smaller than n join (
            if(left < n)
                backTracking(n, result, left + 1, right, str + "(");

            // If the closing bracket is smaller than the closing bracket, add  )
            if (right < left)
                backTracking(n, result, left, right + 1, str + ")");
        }

Function diagram :

原网站

版权声明
本文为[Yuan Sheng Xiao 196]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091102442841.html