C# solution: DFS and '(', ')' count


  • 0
    B
    public class Solution 
    {
        public IList<string> GenerateParenthesis(int n) 
        {
            var result = new List<string>();
    
            DFS(n, 1, 0, new StringBuilder("("), result);
    
            return result;
        }
    
        private void DFS(int n, int left, int right, StringBuilder oneResult, IList<string> result)
        {
            if (left > n) return;
            
            if (left == right && n == left)
            {
                result.Add(oneResult.ToString());
                return;
            }
    
            oneResult.Append('(');
            DFS(n, left + 1, right, oneResult, result);
            oneResult.Remove(oneResult.Length - 1, 1);
    
            if (left > right)
            {
                oneResult.Append(')');
                DFS(n, left, right + 1, oneResult, result);
                oneResult.Remove(oneResult.Length - 1, 1);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.