generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem59.cs
More file actions
39 lines (34 loc) · 1.24 KB
/
Problem59.cs
File metadata and controls
39 lines (34 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/generate-parentheses/">Generate Parentheses</see>.
/// </summary>
public static class Problem59
{
/// <summary>
/// Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
/// Time complexity: O(2^n).
/// Space complexity: O(2^n).
/// </summary>
/// <param name="n">Number of pairs of parentheses.</param>
/// <returns>All combinations of well-formed parentheses.</returns>
public static IList<string> GenerateParenthesis(int n) => GenerateParenthesis("(", 1, 0, n).ToList();
private static IEnumerable<string> GenerateParenthesis(string subCombination, int open, int close, int n)
{
if (close > open || open > n || close > n)
{
yield break;
}
if (open == n && close == n)
{
yield return subCombination;
}
foreach (var combination in GenerateParenthesis(subCombination + "(", open + 1, close, n))
{
yield return combination;
}
foreach (var combination in GenerateParenthesis(subCombination + ")", open, close + 1, n))
{
yield return combination;
}
}
}