Tutorialspoint
Problem
Solution
Submissions

Valid Parentheses Combinations

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to generate all combinations of well-formed parentheses for a given number of pairs n. Implement the GenerateParenthesis(int n) function that returns a list of all possible valid parenthesis combinations.

Example 1
  • Input: n = 3
  • Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
  • Explanation:
    • These are all the valid combinations of 3 pairs of parentheses.
Example 2
  • Input: n = 2
  • Output: ["(())", "()()"]
  • Explanation:
    • These are all the valid combinations of 2 pairs of parentheses.
Constraints
  • 1 <= n <= 8
  • Each generated string should have exactly 2*n characters
  • Each string will only contain '(' and ')' characters
  • All generated strings must be valid (properly closed) parentheses combinations
  • Time Complexity: O(4^n / sqrt(n))
  • Space Complexity: O(n)
RecursionBacktracking FacebookDropbox
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use backtracking/recursion to generate all possibilities
  • Keep track of open and closed parentheses counts
  • Only add an opening parenthesis if you haven't used all n
  • Only add a closing parenthesis if it won't create an invalid combination
  • When both open and closed counts reach n, add the current string to the result list

Steps to solve by this approach:

 Step 1: Create a recursive backtracking function that builds strings character by character
 Step 2: Track the number of open and closed parentheses already used
 Step 3: Only add an opening parenthesis if we haven't used all n of them yet
 Step 4: Only add a closing parenthesis if there are more open than closed parentheses
 Step 5: When the string reaches length 2*n, add it to our result list
 Step 6: Start with an empty string and backtrack to generate all valid combinations
 Step 7: Return the final list of all valid parentheses strings

Submitted Code :