Mid From PDF Coding C# Coding Interview

Generate Parentheses (Well-formed Combinations)?

Follow on:

List<string> GenerateParenthesis(int n)
{
List<string> result = new List<string>();

Generate("", 0, 0, n, result);

return result;
}

void Generate(string current, int open, int close, int max,

List<string> result)
{
if (current.Length == max * 2)
{

result.Add(current);

return;
}
if (open < max)

Generate(current + "(", open + 1, close, max, result);

if (close < open)

Generate(current + ")", open, close + 1, max, result);

}

Explanation:

Use backtracking to add '(' and ')' only when valid.

More from C# Programming Tutorial

All questions for this course
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details