Skip to content

Commit 28e6f27

Browse files
committed
https://leetcode.com/problems/generate-parentheses/
1 parent ce9c11d commit 28e6f27

File tree

2 files changed

+62
-1
lines changed

2 files changed

+62
-1
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System.Text;
2+
3+
namespace LeetCodeSolutions.Backtracking
4+
{
5+
class GenerateParentheses
6+
{
7+
public IList<string> GenerateParenthesis(int n) {
8+
List<string> result = new List<string>();
9+
StringBuilder current = new StringBuilder();
10+
Backtrack(result, current, 0, 0, n);
11+
return result;
12+
}
13+
14+
private void Backtrack(
15+
List<string> result,
16+
StringBuilder current,
17+
int open,
18+
int close,
19+
int max
20+
) {
21+
// Base case: valid combination complete
22+
if (current.Length == max * 2) {
23+
result.Add(current.ToString());
24+
return;
25+
}
26+
27+
// Add open parenthesis if we haven't reached the limit
28+
if (open < max) {
29+
current.Append('(');
30+
Backtrack(result, current, open + 1, close, max);
31+
current.Remove(current.Length - 1, 1); // Backtrack
32+
}
33+
34+
// Add close parenthesis if it won't create imbalance
35+
if (close < open) {
36+
current.Append(')');
37+
Backtrack(result, current, open, close + 1, max);
38+
current.Remove(current.Length - 1, 1); // Backtrack
39+
}
40+
}
41+
42+
[Test(Description = "https://leetcode.com/problems/generate-parentheses/")]
43+
[Category("Medium")]
44+
[Category("LeetCode")]
45+
[Category("Generate Parentheses")]
46+
[TestCaseSource(nameof(Input))]
47+
[Category("TopInterview")]
48+
[Category("Backtracking")]
49+
public void Test1((int Output, int Input) item)
50+
{
51+
var response = GenerateParenthesis(item.Input);
52+
Assert.That(response.Count, Is.EqualTo(item.Output));
53+
}
54+
55+
public static IEnumerable<(int Output, int Input)> Input =>
56+
new List<(int Output, int Input)>()
57+
{
58+
(5, 3),
59+
};
60+
}
61+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
163163
| 103 | Permutations | Medium ||
164164
| 104 | Combination Sum | Medium ||
165165
| 105 | N-Queens II | Hard ||
166-
| 106 | Generate Parentheses | Medium | |
166+
| 106 | Generate Parentheses | Medium | |
167167
| 107 | Word Search | Medium ||
168168
| <br> Divide &amp; Conquer<br> | | | |
169169
| 108 | Convert Sorted Array to Binary Search Tree | Easy ||

0 commit comments

Comments
 (0)