You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
3
+
Constraints: 1 <= n <= 8
4
+
Problem source: https://leetcode.com/problems/generate-parentheses/
5
+
"""
6
+
7
+
classSolution:
8
+
defgenerateParenthesis(self, n):
9
+
valid= []
10
+
11
+
# Helper function to generate valid combinations
12
+
defgenerate(s, open_count, close_count):
13
+
ifopen_count==0andclose_count==0:
14
+
valid.append(s)
15
+
return
16
+
17
+
ifopen_count>0:
18
+
s+='('
19
+
generate(s, open_count-1, close_count)
20
+
s=s[:-1]
21
+
22
+
ifclose_count>0andopen_count<close_count:
23
+
s+=')'
24
+
generate(s, open_count, close_count-1)
25
+
s=s[:-1]
26
+
27
+
ifn<0:
28
+
raiseValueError("Input value must be non-negative")
29
+
30
+
# Start the generation process with an empty string and n opening and closing parentheses
31
+
generate('', n, n)
32
+
"""
33
+
The function employs backtracking to generate all valid combinations of n pairs of parentheses. It maintains two counters, open_count and close_count, representing available open and close parentheses.
34
+
35
+
It starts with an empty string s and both counters set to n.
36
+
37
+
It recursively explores two possibilities:
38
+
39
+
Adding an open parenthesis '(' if open_count > 0.
40
+
Adding a close parenthesis ')' if close_count > 0 and there are open parentheses available (i.e., open_count < close_count).
41
+
When both counters reach zero, it means a valid combination is formed, and it's added to the valid list.
42
+
43
+
The code then tries different combinations by backtracking (removing the last added parenthesis) and continues until all possibilities are exhausted.
44
+
45
+
The input is validated to ensure it's a non-negative integer, and a ValueError is raised for invalid input.
46
+
47
+
The valid combinations are returned as the result.
48
+
"""
49
+
50
+
returnvalid
51
+
52
+
53
+
try:
54
+
# Input the value of n from the user
55
+
n=int(input("Enter a value for n: "))
56
+
57
+
# Create an instance of the Solution class and generate valid combinations
58
+
solution=Solution()
59
+
result=solution.generateParenthesis(n)
60
+
61
+
# Return the valid combinations
62
+
print(result)
63
+
exceptValueError:
64
+
print("Invalid input. Please enter a non-negative integer.")
0 commit comments