Simple to understand C# back tracking solution


  • 0
    F

    The recursive helper method keeps track of what to do based on 2 parameters: number of parans left to open and number left to close. Initially both are n.

    public class Solution {
    public IList<string> GenerateParenthesis(int n) {
        if (n == 0) return new List<string>();
        var op = new List<string>();
        var part = new List<char>();
        GenerateParanHelper (n, n, part, op);
        return op;
    }
    
    public void GenerateParanHelper(int openRem, int closeRem, List<char> partial, List<string> op) {
        if (openRem == 0 && closeRem == 0)
        {
            op.Add(new string(partial.ToArray()));
            return;
        }
        
        if (openRem > 0)
        {
            partial.Add('(');
            GenerateParanHelper(openRem - 1, closeRem, partial, op);
            partial.RemoveAt(partial.Count - 1);
        }
        
        if (closeRem > openRem)
        {
            partial.Add(')');
            GenerateParanHelper(openRem, closeRem - 1, partial, op);
            partial.RemoveAt(partial.Count - 1);
        }
    }
    

    }


Log in to reply
 

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