|
| 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 | +} |
0 commit comments